Android web service error in http - android

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.

Related

Move One activity to Another Activity using function

MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name = (EditText) findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.password);
submit_btn = (Button) findViewById(R.id.submit);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sender s = new Sender(v.getContext(),urlAddress,user_name,password);
s.execute();
cxt = getApplicationContext();
}
});
}
public void GoUserActivity(){
Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);
startActivity(i);
}
}
Sender.java
package com.example.prakash.cinihive;
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText user_name,password;
String UserName,Password;
ProgressDialog pd;
MainActivity main = new MainActivity();
public Sender(Context c, String urlAddress, EditText user_name, EditText password) {
this.c = c;
this.urlAddress = urlAddress;
this.user_name = user_name;
this.password = password;
UserName = user_name.getText().toString();
Password = password.getText().toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("send");
pd.setMessage("Sending..Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response !=null){
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
//Log.d("Response",response);
if(response.equals("false")){
Toast.makeText(c,"Invalid Credentials",Toast.LENGTH_LONG).show();
}
else{
main.GoUserActivity();
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
}
user_name.setText("");
password.setText("");
}
else{
Toast.makeText(c,"Un succesfullll",Toast.LENGTH_LONG).show();
}
}
public String send(){
HttpURLConnection con = Connector.connect(urlAddress);
//Toast.makeText(c,con.toString(),Toast.LENGTH_LONG).show();
if(con==null){
Toast.makeText(c,"Connection Null",Toast.LENGTH_LONG).show();
return null;
}
try{
// Log.d("Connection status","Connection not null");
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPack(UserName,Password).Packdata());
bw.flush();
bw.close();
os.close();
int responseCode = con.getResponseCode();
Log.d("MYINT","Response Id :"+responseCode);
if(responseCode==con.HTTP_OK){
Log.d("Response code","Response code success");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while((line=br.readLine())!=null){
response.append(line);
}
br.close();
return response.toString();
}else{
Log.d("Response code","Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my code My problem was Intent Statement Not working in GoUserActivity funtion
At the same time Intent Statement Working well in OnCreate function.
When I try to run inside GoUserActivity,it will raise the runtime error(NullPoniterException "Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);")
I think you'll find things work better if you move your AsyncTask inside MainActivity as an inner class. You'll be able to call GoUserActivity() without having to new another instance of MainActivity, which you should never do.

How to use Handler in AsynkTask in android

I am fetching data from server using AsynkTask which works fine but I want to use handler in AsynkTask to reduce load from main Thread.How can I use Handler in AsynkTask. Kindly help me to solve this problem.
Here is my code.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://192.168.0.999:8080/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setBackgroundColor(Color.TRANSPARENT);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
public Dialog m_Dialog;
public ProgressBar m_ProgressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_Dialog = new Dialog(getActivity());
m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
m_Dialog.setContentView(R.layout.progress_bar);
showProgress("Please wait while Logging...");// showing progress ..........
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
hideProgress();// hide progressbar after getting response from server......
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
getResponse();// getting response from server
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
showToast("Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
showToast("Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
showToast("Invalid Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
showToast("You are blocked as You finished you all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
showToast("Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
showToast("User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
showToast("Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void showToast(String message) {// method foe showing taost message
Toast toast = Toast.makeText(getActivity(), "" + message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
public void showProgress(String message) {
m_ProgressBar = (ProgressBar) m_Dialog.findViewById(R.id.progress_bar);
TextView progressText = (TextView) m_Dialog.findViewById(R.id.progress_text);
progressText.setText("" + message);
progressText.setVisibility(View.VISIBLE);
m_ProgressBar.setVisibility(View.VISIBLE);
m_ProgressBar.setIndeterminate(true);
m_Dialog.setCancelable(false);
m_Dialog.setCanceledOnTouchOutside(false);
m_Dialog.show();
}
public void hideProgress() {
m_Dialog.dismiss();
}
}
}
As per android docs here
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
And loading data from URL with Handler is not a good thing. Instead use Executor or ThreadPoolExecutor to do heavy background tasks.
You Can Use
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getResponse();
}
});
you can do like this:
class MyAsyncTask extends AsyncTask<Object,Object,Object>{
Private Context c;
private Handler handler;
private final static int YOUR_WORK_ID = 0x11;
public MyAsyncTask(Context c,Handler handler){
this.c = c;
this.handler = handler;
}
protected Object doInBackground(Object... params){
//do your work
...
Message m = handler.obtainMessage();
m.what = YOUR_WORK_ID;
...
handler.sendMessage().sendToTarget();
}
}
And in your fragment ,you can init a handler as params to MyAsyncTask,and deal with you work in handleMessage();

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

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.

Response:wrong. [User registration via android app using http post not working]

I was able to successfully make login work. Now, I am stuck up with registration. Response is wrong.
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
register();
}
}).start();
}
}
void register() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.dismiss();
}
});
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
} catch (Exception e) {
mDialog.dismiss();
Log.i(LOGTAG, "Exception found"+ e.getMessage());
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Please Note: Every activities are registered in Manifest, INTERNET permission also included.
php file:
include "dbconnection.php";
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO register
Values ('', '$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data);
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
I don't understand why it keeps on saying Response is : Wrong. Tired of spending almost a day .. I am here seeking help.
Excuse me if my questions seems naive.
Thank you in advance.
try below code:-
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null)
{
InputStream in = httpResponse.getEntity().getContent();
result = ConvertStreamToString.convertStreamToString(in);
// System.out.println("result =>" + result);
}
convertStreamToString method
public String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
do not under stand :-
HttpResponse httpResponse = httpClient.execute(httpPost); // getting response from server
// where you use this response and why using below line or whats the benefit of below line
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
Follow that tutorial very usefull, and clear how to work on json webservices with android.
How to connect Android with PHP, MySQL
Try this code using AsyncTask
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new RegisterUser().execute();
}
}
public class RegisterUser extends AsyncTask<Void, Void, String>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Hope this helps you!!!
If its not working please let me know i will try to help more...
Try using Volley if not. It's faster than the ussual HTTP connection classes.
Example:
RequestQueue queue = Volley.newRequestQueue(this);
String url = "url";
JSONObject juser = new JSONObject();
try {
juser.put("locationId", locID);
juser.put("email", email_input);
juser.put("password", password_input);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
Like #Andrew T suggested , I am posting my solution.
The mysql_error()helped me debug the issue. mysql_error() displayed in the Logcat that "register table is not found" .. but the table name is registers. I was missing "s" at the end.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO registers(id, fullname, email, password)
Values ('','$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data) or die(mysql_error());
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
Everything worked perfect after that. Again, thank you all for your time and solutions. Everyone's suggestions are great, but I can not accept any answer at this point.. sorry:(

login page with httpget and asynctask in android

Hi I'm new to android and have task to create a login page that will connect with server and check user exist using http Get and AsyncTask and PHP API for this is ready. i went through few tutorials on AsyncTask and i understood but i m not sure how to work with http Get and AsyncTask. can anyone please help how to link both and create login page.
P.S: i have two EditText to accept username and password and two Buttons one for login and other for register and have corresponding DB as well.
This is sample code-
public class LoginActivity extends Activity
{
Intent i;
Button signin, signup;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences, pref;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
SharedPreferences.Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
signup = (Button) findViewById(R.id.signup);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes"))
{
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
signin.setEnabled(false);
signup.setEnabled(false);
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals(""))
{
Toast.makeText(LoginActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
else
{
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(name.matches(emailPattern))
new LoginTask().execute();
signin.setEnabled(false);
signup.setEnabled(false);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Move_next();
}
});
}
public void Move_to_next()
{
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
startActivity(new Intent(LoginActivity.this, SplashActivity.class));
finish();
}
};
handle.postDelayed(delay,2000);
}
public void Move_next()
{
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
finish();
}
#SuppressLint("NewApi")
private class LoginTask extends AsyncTask <Void, Void, String>
{
#SuppressLint("NewApi")
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://website.com/yourpagename.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y')
{
Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
}
else
{
Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
}
}
}

Categories

Resources