How to pass extra data from this activity to the next activity? - android

how to pass extra data from this activity?
public class DetailActivity extends Activity {
#Override
public void onBackPressed() {
}
#SuppressLint("NextAPI")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Button btnForum = (Button) findViewById(R.id.btnForum);
Button btnKuis = (Button) findViewById(R.id.btnKuis);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
showInfo();
final Button btnLogout = (Button) findViewById(R.id.btnBack);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(DetailActivity.this,MainActivity.class);
startActivity(newActivity);
}
});
btnForum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forum = new Intent(DetailActivity.this, Forum.class); ;
startActivity(forum);
}
});
btnKuis.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class); ;
startActivity(kuis);
}
});
}
public void showInfo(){
final TextView tNrp = (TextView)findViewById(R.id.txtNrp);
final TextView tName = (TextView)findViewById(R.id.txtName);
final TextView tSmt = (TextView)findViewById(R.id.txtSmt);
final TextView tStatus = (TextView)findViewById(R.id.txtStatus);
String url = "http://xxx/blabla/getID.php";
Intent intent = getIntent();
String MhsID = intent.getStringExtra("idm");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMhsID", MhsID));
String resultServer = getHttpPost(url,params);
String strMemberID = "";
String strNrp = "";
String strPassword = "";
String strName = "";
String strSmt = "";
String strStatus = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strNrp = c.getString("idm");
strName = c.getString("nama-mahasiswa");
strSmt = c.getString("semester");
strStatus = c.getString("status-mahasiswa");
if(!strMemberID.equals(""))
{
tNrp.setText(strNrp);
tName.setText(strName);
tSmt.setText(strSmt);
tStatus.setText(strStatus);
}
else
{
tNrp.setText("-");
tName.setText("-");
tSmt.setText("-");
tStatus.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
this DetailActivity already have extra data from the previous activity, but i need to pass extra data "idm" to Kuisioner Activity. can anyone teach me how to do that? please this is really important to me :(

Declare String MhsID as class level member field like,
public class DetailActivity extends Activity {
private String MhsID = null;
Now in showInfo get Intent data like,
public void showInfo(){
....
Intent intent = getIntent();
MhsID = intent.getStringExtra("idm");
....
And pass values of MhsID to Kuisioner Activity using putExtra() via Intent as you did in previous activity
btnKuis.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class);
kuis.putExtra("idm",MhsID);
startActivity(kuis);
}
});
And get String idm in Kuisioner Activity same as this activity.

in DetailActivity.java:
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class);
kuis.putExta("Key_hossam", "value"); // just add this line
startActivity(kuis);
in Kuisioner.java:
inside the onCreate method just write these lines
Intent intent= getIntent();
Bundle b = intent.getExtras();
if(b!=null)
{
String value =(String) b.get("Key_hossam");
}
}

It is all explained HERE.
Just add this line of code:
intent.putExtra(name, value);
So starting new Kuisioner activity should look like this:
String value = "Example value"
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class);
kuis.putExtra("idm", value);
startActivity(kuis);

If you are working with too many variables, and want to pass data among activities, I suggest make your Activity-variables static , and use with class name, no more maintaining variables.
Note : I assume you are using Fragments, you may come back to activities again n again.

Related

Getting NullpointerException While Printing Data from SharedPreference for first time in another activity

Here is the code i am not getting any value in another activity from shared preference for first time even though json response is been saved in explorer but when i click the button for second time and go to that activity again i am getting the value but for the first time i am not getting any value please help thanks
public class MainActivity extends AppCompatActivity {
TextInputEditText name, addresssss, address1111, city, state, country, postalcode, landmark,mobiles;
TextView namee, addresss, address11, cityy, statee, countryy, postalcodee, landmarkk,hhhh;
String nameee, nam, ad, ad1, ci, sta, cou, pos, land, nameeee;
Button Submit;
String ggg;
JSONObject object;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
namee = (TextView) findViewById(R.id.namee);
landmarkk = (TextView) findViewById(R.id.landmarkk);
addresss = (TextView) findViewById(R.id.addresss);
address11 = (TextView) findViewById(R.id.address11);
cityy = (TextView) findViewById(R.id.cityy);
statee = (TextView) findViewById(R.id.statee);
countryy = (TextView) findViewById(R.id.countryy);
postalcodee = (TextView) findViewById(R.id.postalcodee);
hhhh=(TextView)findViewById(R.id.hhhh);
mobiles=(TextInputEditText)findViewById(R.id.mobiles);
name = (TextInputEditText) findViewById(R.id.name);
addresssss = (TextInputEditText) findViewById(R.id.address);
address1111 = (TextInputEditText) findViewById(R.id.address1);
city = (TextInputEditText) findViewById(R.id.city);
state = (TextInputEditText) findViewById(R.id.state);
country = (TextInputEditText) findViewById(R.id.country);
postalcode = (TextInputEditText) findViewById(R.id.postalcode);
landmark = (TextInputEditText) findViewById(R.id.landmark);
Submit = (Button) findViewById(R.id.Submit);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new SendRequest().execute();
nameee = name.getText().toString().trim();
if (TextUtils.isEmpty(name.getText().toString())) {
return;
}
ad = addresssss.getText().toString();
if (TextUtils.isEmpty(addresssss.getText().toString())) {
return;
}
ad1 = address1111.getText().toString();
if (TextUtils.isEmpty(address1111.getText().toString())) {
return;
}
ci = city.getText().toString();
if (TextUtils.isEmpty(city.getText().toString())) {
return;
}
sta = state.getText().toString();
if (TextUtils.isEmpty(state.getText().toString())) {
return;
}
cou = country.getText().toString();
if (TextUtils.isEmpty(country.getText().toString())) {
return;
}
pos = postalcode.getText().toString();
if (TextUtils.isEmpty(postalcode.getText().toString())) {
return;
}
land = landmark.getText().toString().trim();
if (TextUtils.isEmpty(landmark.getText().toString())) {
return;
}
nameeee=mobiles.getText().toString().trim();
if (TextUtils.isEmpty(mobiles.getText().toString())) {
return;
}
else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
}
});
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://services.sweken.com/api2/information/checkRegionByPincode");
JSONObject postDataParams = new JSONObject();
postDataParams.put("address", ad);
postDataParams.put("address_1", ad1);
postDataParams.put("pincode", pos);
postDataParams.put("land_mark", land);
postDataParams.put("name", nameee);
postDataParams.put("mobile_no", nameeee);
Log.e("params", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds *);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
try {
object = new JSONObject(result);
ggg = object.getString("customer_id");
Log.d("customer",ggg);
SharedPreferences.Editor editt = sharedPreferences.edit();
editt.putString("CUSTOMER_ID", ggg);
editt.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
public class Main2Activity extends AppCompatActivity {
String idddd;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
text = (TextView) findViewById(R.id.text);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
idddd = sharedPreferences.getString("CUSTOMER_ID", "");
text.setText(idddd);
}
}
Here is the problem, you execute your network calls when the button is clicked, and new intent is directly started without waiting for network call's response, so it will not work for the first time.
Solution is to chain the operation in the Submit button's onClick validation stuff.
To chain the operations, extract this code block like this,
public void goToNextActivity(){
nameee = name.getText().toString().trim();
if (TextUtils.isEmpty(name.getText().toString())) {
return;
}
ad = addresssss.getText().toString();
if (TextUtils.isEmpty(addresssss.getText().toString())) {
return;
}
ad1 = address1111.getText().toString();
if (TextUtils.isEmpty(address1111.getText().toString())) {
return;
}
ci = city.getText().toString();
if (TextUtils.isEmpty(city.getText().toString())) {
return;
}
sta = state.getText().toString();
if (TextUtils.isEmpty(state.getText().toString())) {
return;
}
cou = country.getText().toString();
if (TextUtils.isEmpty(country.getText().toString())) {
return;
}
pos = postalcode.getText().toString();
if (TextUtils.isEmpty(postalcode.getText().toString())) {
return;
}
land = landmark.getText().toString().trim();
if (TextUtils.isEmpty(landmark.getText().toString())) {
return;
}
nameeee=mobiles.getText().toString().trim();
if (TextUtils.isEmpty(mobiles.getText().toString())) {
return;
}
else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
}
then call this method from asynctask's protected void onPostExecute(String result).
#Override
protected void onPostExecute(String result) {
try {
object = new JSONObject(result);
ggg = object.getString("customer_id");
Log.d("customer",ggg);
SharedPreferences.Editor editt = sharedPreferences.edit();
editt.putString("CUSTOMER_ID", ggg);
editt.apply();
//**after all needed data is persisted to preferences.**
goToNextActivity();
} catch (JSONException e) {
e.printStackTrace();
}
}
Hope this help.

Passing data from Activity to Fragment in android

I have just started Android and i am working on Simple Login Page,where user can use their email and password to login with some conditions while login. When user login as a "store owner",his name and email is shown on the next page (i.e on the Fragment class) which is working fine but whenever user login as a "public user",his name and email is not showing on the next page.
Note: I am using webservices and SharedPreferences to fetch and save data.
Thanks in Advance
Here is my code
LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
EditText login_emailid, login_password;
String str_login_email, str_login_password;
Button login_button;
public static final String MY_PREFS_NAMEs = "MyPrefsFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_button = (Button) findViewById(R.id.loginBtn);
login_emailid = (EditText) findViewById(R.id.login_emailid);
login_password = (EditText) findViewById(R.id.login_password);
login_button = (Button) findViewById(R.id.loginBtn);
login_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == login_button) {
str_login_email = login_emailid.getText().toString();
str_login_password = login_password.getText().toString();
if (str_login_email.isEmpty()) {
login_emailid.setError("Enter your email");
} else if (str_login_password.isEmpty()) {
login_password.setError("Password Please");
} else {
new AsyncTaskRunner().execute();
}
}
}
}
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public String connection(String action) {
String result = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://beta.gkninternational.life/webservice/user_login.php");// replace with your url
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(new BasicNameValuePair(
"action", action));
nameValuePairList.add(new BasicNameValuePair(
"Email", str_login_email));
nameValuePairList.add(new BasicNameValuePair(
"Password", str_login_password));
try {
Log.e("nameValuePairList", " " + nameValuePairList);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient
.execute(httpPost);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
result = stringBuilder.toString();
Log.e("result", stringBuilder.toString());
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("First Exception coz of HttpResponese :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second Exception coz of HttpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return result;
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog mProgressBar;
String resp;
int success;
String message;
String name, email, password, userrole, userpic, iddd;
String storeId,storeName;
SharedPreferences sharedPreferencesLogin;
SharedPreferences.Editor editor;
#Override
protected String doInBackground(String... params) {
String result = connection("Login_Activity");
try {
sharedPreferencesLogin = getSharedPreferences(MY_PREFS_NAMEs, Context.MODE_PRIVATE);
editor = sharedPreferencesLogin.edit();
JSONObject jsonObject = new JSONObject(result);
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
iddd = jsonObject.getString("UserId");
name = jsonObject.getString("FirstName");
email = jsonObject.getString("Email");
userrole = jsonObject.getString("UserRole");
storeId = jsonObject.getString("StoreId");
storeName = jsonObject.getString("StoreName");
editor.putString("UserId", name);
editor.putString("FirstName", name);
editor.putString("Email", email);
editor.putString("userrole", userrole);
editor.putString("storeIdLogin", storeId);
editor.putString("StoreNameLogin", storeName);
editor.apply();
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
mProgressBar.dismiss();
if (success == 2) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
} else if (success == 1) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
if(userrole.equals("store_owner"))
{
if(storeName.equals("Dummy")){
startActivity(new Intent(LoginActivity.this, EditActivity.class));
finish();
}
else{
Intent intentt = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intentt);
finish();
}
}
else{
Intent intentuser = new Intent(LoginActivity.this, AfterSplash.class);
startActivity(intentuser);
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressBar = new ProgressDialog(LoginActivity.this);
mProgressBar.setMessage("Connecting to server");
mProgressBar.setCancelable(false);
mProgressBar.show();
}
}
Frament class
public class MyFragment extends Fragment{
SharedPreferences sharedPreferencesLogin;
public static final String MY_PREFS_NAMEs = "MyPrefsFiles";
TextView names,emails;
String str_names,str_emails;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_my, container, false);
sharedPreferencesLogin= getActivity().getSharedPreferences(MY_PREFS_NAMEs, Context.MODE_PRIVATE);
names=(TextView)layout.findViewById(R.id.names);
emails=(TextView)layout.findViewById(R.id.emails);
str_names= sharedPreferencesLogin.getString("FirstName","");
str_emails= sharedPreferencesLogin.getString("Email","");
names.setText(str_names);
emails.setText(str_emails);
}
}
try this to set Shared Pref
String userId=yourstring;
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(youractivity.this);
Editor edit = settings.edit();
edit.putString("name", userId);
settings.commit;
to get shared pref
SharedPreferences settins = PreferenceManager
.getDefaultSharedPreferences(Youractivity.this);
name=settings.getString("name", "anon");
You have to use a bundle and a serializable object to pass.:
From the activity:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(ARGUMENT_KEY, objectSerializable);
fragment.setArguments(bundle); showFragment(fragment)
On the fragment:
Bundle bundle = this.getArguments();
if (bundle != null) {
Object neededObject = bundle.getSerializable(ser_key)
}
Override newInstance() method in your fragment like this.
public static YourFragment newInstance(Bundle bundle) {
ActivityFeedListFragment fragment = new ActivityFeedListFragment();
fragment.setArguments(bundle);
return fragment;
}
And pass bundle object.

Android Get the data from User And pass the data to multiple activities

I have android app for login, when user gives login details that data have to pass in multiple activities.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username=(EditText)findViewById(R.id.user_name);
passwrd=(EditText)findViewById(R.id.Pass_word);
login=(Button)findViewById(R.id.Login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = username.getText().toString();
String password = passwrd.getText().toString();
new Mytask().execute(email, password);
}
});
}
I want to pass email and password to multiple activities..
I just tried Bundle.
I stored email value as "name".
And i just passed the value to another activity(Below code).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testpage);
Entertext = (EditText) findViewById(R.id.tex_id);
Submit = (Button) findViewById(R.id.sub_mit);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Text = Entertext.getText().toString();
Intent i = getIntent();
Bundle b = i.getBundleExtra("personBdl");
String name = b.getString("name");
new Mytask().execute(name,Text);
}
});
private class Mytask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
StringBuilder dta = null;
try {
URL url = new URL("http://xxxyyy.com/insert.php?user=" + params[0] + "&value=" + params[1]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
} else {
//Handle else
}
return dta.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
Email has passed as "name"(bundle).
"name" value passed as params[0] to my php file.
But params[0] not passed to my php file.
Could you please help me with this. Thank you.
You should probably use SharedPreferences instead of Bundle.
Save data like this:
SharedPreferences sPref;
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString("email", etText.getText().toString());
ed.putString("password", etText.getText().toString());
ed.commit();
And get it in your activities like this:
sPref = getPreferences(MODE_PRIVATE);
String email = sPref.getString("email", "");
String password = sPref.getString("password", "");
etText.setText(savedText);
And I also recommend you to use it in separate thread.

Android web service error in http

In my project , to access the webservice am using http class which is not working properly and my project stops.
Can someone tell me an alternate way for accessing the webservice instead of using http.
Thank you in advance
class httpclass {
String result;
public String server_conn(String user_url)
{
// String user_url="";
String user_url3=user_url.replaceAll(" ","%20");
String user_url2=user_url3.replaceAll("\n","%0D");
HttpClient client = new DefaultHttpClient();
HttpGet siteRequest = new HttpGet(user_url2);
StringBuilder sb = new StringBuilder();
HttpResponse httpResponse;
try {
httpResponse = client.execute(siteRequest);
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
String line = null;
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
log in form
public class LoginForm extends FragmentActivity {
/** Called when the activity is first created. */
TextView txt1, txt2, err,forget;
EditText name;
EditText pass;
Button click,vend;
CheckBox savepass;
Button newuser;
Button signin;
#SuppressWarnings("unused")
private Cursor signin1;
SharedPreferences sharedPreferences=null;
public static String str1, str2;
public static String result;
public static String username;
ProgressDialog myProgressDialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); BugSenseHandler.initAndStartSession(this, "68640bea");
setContentView(R.layout.login);
vend=(Button)findViewById(R.id.vend);
name = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
savepass=(CheckBox)findViewById(R.id.savepass);
Button cancel = (Button) findViewById(R.id.cancel);
//Button back = (Button) findViewById(R.id.back);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent second = new Intent( LoginForm.this,canceluser.class);
startActivity(second);
finish();
}
});
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
String name1=sharedPreferences.getString("p_name", "");
name.setText(name1.toString());
String pass1=sharedPreferences.getString("p_pass", "");
pass.setText(pass1.toString());
//s forget=(TextView)findViewById(R.id.forget);
signin = (Button) findViewById(R.id.signin);
click = (Button) findViewById(R.id.click);
newuser = (Button) findViewById(R.id.signup);
vend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://www.iwedplanner.com/vendor/vendorhome.aspx"));
startActivity(viewIntent);
}});
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(LoginForm.this, forgetpwd.class);
startActivity(intent1);
finish();
}});
signin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(name.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Username");
name.requestFocus();
}
else if(pass.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Password");
pass.requestFocus();
}
else
{
str1 = name.getText().toString();
str2 = pass.getText().toString();
boolean value = false;
// validuser();
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
value = true;
openconn(str1, str2);
}
else
{
alertbox("Message!", "No Internet Connection!");
}
}
}
});
newuser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newuser();
}
});
}
public void openconn(String strr1, String strr2)
{
if (!strr1.equals("") && !strr2.equals(""))
{
err = (TextView) findViewById(R.id.err);
// String user_url = "http://iwedplanner.com/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
// alertbox("",""+result);
if (result != null)
{
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if (result.equals("InvalidUser "))
{
Dialog locationError = new AlertDialog.Builder(
LoginForm.this).setIcon(0).setTitle("Message!")
.setPositiveButton(R.string.yes, null).setMessage(
"Sorry, Invalid Username or Password ")
.create();
locationError.show();
name.requestFocus();
}
else if(result.equals(strr1))
{
// Toast.makeText(getBaseContext(),"Valid User",Toast.LENGTH_SHORT).show();
if(savepass.isChecked())
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name",name.getText().toString());
//editor.putString("p_pass",pass.getText().toString());
editor.commit();
}
else
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name", "");
editor.putString("p_pass","");
editor.commit();
}
validuser();
}
else
{
alertbox("Message!","Error in network connection");
}
}
}
}
public void validuser()
{
username=str1;
name.setText("");
pass.setText("");
Intent userintent = new Intent(this, welcomeuser1.class);
//userintent.putExtra("name5",str1);
//Intent userintent=new Intent(this,WeddingInfo.class);
startActivity(userintent);
finish();
}
public void newuser() {
Intent userintent1 = new Intent(this, newuserform.class);
startActivity(userintent1);
finish();
}
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
// // EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
// EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
}
Error:duplicate files during packaging of APK C:\Users\sentientit\Documents\Wed Studio\app\build\outputs\apk\app-debug-unaligned.apk
Path in archive: META-INF/LICENSE.txt
Origin 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
1 Origin 2: C:\Users\sentientit.gradle\caches\modules-2\files-2.1\joda-
time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can ignore those files in your build.gradle:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
Error:Execution failed for task ':app:packageDebug'.
Duplicate files copied in APK META-INF/LICENSE.txt
File 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
File 2: C:\Users\sentientit\.gradle\cache``s\modules-2\files-2.1\joda-time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can do this way:
AsyncTask for Web service:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
String serverGETResponse = getJsonDataStringFormat("Your_Url", "GET", "", "LOGIN_ACTIVITY");
String serverPOSTResponse = getJsonDataStringFormat("Your_Url", "POST", "YOUR_JSON_STRING", "LOGIN_ACTIVITY");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
Now Get Response from server in Background thread:
public static String getJsonDataStringFormat(String url, String method,String jObjStr, String tag) {
InputStream is = null;
String Root_Response = null;
HttpResponse httpResponse;
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient;
HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
try {
httpClient = new DefaultHttpClient(httpParameters);
url = url.replace(" ", "%20");
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jObjStr));
httpResponse = httpClient.execute(httpPost);
is = httpResponse.getEntity().getContent();
} else if (method == "GET") {
HttpGet httpGet = new HttpGet(new URI(url));
httpResponse = httpClient.execute(httpGet);
is = httpResponse.getEntity().getContent();
}
Root_Response = convertStreamToString(is);
Log.i(tag, Root_Response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (URISyntaxException e) {
e.printStackTrace();
}
return Root_Response;
}
Convert Server's Response to String:
public static String convertStreamToString(InputStream inputStream)
throws IOException {
if (inputStream != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
inputStream.close();
}
return sb.toString();
} else {
return "";
}
}
Hope it will help you.
call the method server_conn() inside AsyncTask , and pass the url
private class AsyncTaskTest extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
server_conn(strings[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
and call the asynctastk using below syntax
new AsyncTaskTest().execute(url);
You are facing NetworkOnMainThread exception all you have to do is add this code :
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
For more details you can check developer site.

Using AsyncTasnk and return value and compare with other value

I want to return a value from AsyncTask and I want to compare with the value contents and at the and if they match I want to send the value where I take it from AsyncTasnk to the other intent. I hope I explained it properly.
and this is the code :
public class MainActivity extends Activity {
Button ButtonClick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txt = (TextView) findViewById(R.id.textView1);
ButtonClick = (Button) findViewById(R.id.qrReader);
ButtonClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
GetProduts GP = new GetProduts();
txt.setText(GP.execute().toString());
}
});
// Intent i = new Intent(MainActivity.this,IndexActivity.class);
// startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
final String contents = intent.getStringExtra("SCAN_RESULT");
//I want to compare this value
}
} else if (resultCode == RESULT_CANCELED) {
}
}
#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;
}
public class GetProduts extends AsyncTask<ArrayList<Product>, Void, ArrayList<Product>> {
Product p;
final ArrayList<Product> productIdList = new ArrayList<Product>();
#Override
protected ArrayList<Product> doInBackground(ArrayList<Product>... params) {
HttpClient httpclient = new DefaultHttpClient();
GeneralConstans GC = new GeneralConstans();
// Products will be stated in memory
HttpPost httpget = new HttpPost(GC.UrlProducts);
HttpResponse response;
String result = null;
try {
HttpContext ctx = new BasicHttpContext();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
response = httpclient.execute(httpget, ctx);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
JSONArray arr = new JSONArray(result);
Gson gson = new Gson();
if (arr.length() > 0) {
for (int j = 0; j < arr.length(); j++) {
p = gson.fromJson(arr.getString(j), Product.class);
productIdList.add(p);
}
}
return productIdList;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException e) {
/*
* if (checkAbortStatus(e.getMessage()) == true) {
* handler.sendEmptyMessage(0); }
*/
} catch (IOException e) {
/*
* if (checkAbortStatus(e.getMessage()) == true) {
* handler.sendEmptyMessage(0); }
*/
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Product> result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Declare contents under Button ButtonClick; as:
String contents = "";
In onActivityResult(), replace:
final String contents = intent.getStringExtra("SCAN_RESULT");
with:
contents = intent.getStringExtra("SCAN_RESULT");
result in onPostExecute(ArrayList<Product> result) is productIdList. Change your onPostExecute() to:
#Override
protected void onPostExecute(ArrayList<Product> result) {
super.onPostExecute(result);
if (result != null) {
for (int i = 0; i < result.size(); i++) {
if(result.get(i).toString().equals(contents) {
// Do something
}
}
}
}
Also, the following doesn't look correct:
public void run() {
GetProduts GP = new GetProduts();
txt.setText(GP.execute().toString());
}
Instead try this:
public void run() {
new GetProduts().execute();
}
And declare txt as TextView txt; under Button ButtonClick;. Now, add the following line to your onPostExecute():
txt.setText(....); // Replace .... with whatever you are trying to set.
Edit 1:
To start another activity:
if(result.get(i).toString().equals(contents) {
// Change "OtherActivity" to the name of the activity you want to start
Intent newIntent = new Intent(MainActivity.this, OtherActivity.class);
newIntent.putExtra("My_Extra", result.get(i).toString());
startActivity(newIntent);
}
To retrieve this String in the other activity:
String extraString = getIntent().getStringExtra("My_Extra");

Categories

Resources