Creating a android app that sends POST request to PHP [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've already tried several options to send a post request from an android app to a server running a PHP file
I need to send a POST Request where the following parameters: id = 0 & balance = 666
I have the following code on my app and wen the app goes to send the request the app crashes
Can some one help?
ANDROID CODE:
package com.example.hk300.jsonpost;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.R.id.message;
public class MainActivity extends AppCompatActivity {
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
private static final int START_LEVEL = 1;
private int mLevel;
private Button mNextLevelButton;
private InterstitialAd mInterstitialAd;
private TextView mLevelTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the next level button, which tries to show an interstitial when clicked.
mNextLevelButton = ((Button) findViewById(R.id.next_level_button));
mNextLevelButton.setEnabled(false);
mNextLevelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInterstitial();
}
});
// Create the text view to show the level number.
mLevelTextView = (TextView) findViewById(R.id.level);
mLevel = START_LEVEL;
// Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
mInterstitialAd = newInterstitialAd();
loadInterstitial();
// Toasts the test ad message on the screen. Remove this after defining your own ad unit ID.
Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mNextLevelButton.setEnabled(true);
}
#Override
public void onAdFailedToLoad(int errorCode) {
mNextLevelButton.setEnabled(true);
}
#Override
public void onAdClosed() {
// Proceed to the next level.
goToNextLevel();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
goToNextLevel();
}
}
private void loadInterstitial() {
// Disable the next level button and load the ad.
mNextLevelButton.setEnabled(false);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mLevelTextView.setText("Level " + (++mLevel));
mInterstitialAd = newInterstitialAd();
loadInterstitial();
new BackgroundTask().execute();
}
public class BackgroundTask extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute(){
//Do UI operation here and onPostExecute
//TextView textview = (TextView)findViewById(R.id.credits);
//textview.setText(message);
}
#Override
protected String doInBackground(Void... params) {
OutputStream os = null;
InputStream is = null;
HttpURLConnection conn = null;
String contentAsString = null;
try {
URL url = new URL("https://disjunct-swabs.000webhostapp.com/testapp.php");
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", "0");
jsonObject.put("balance", "666");
String message = jsonObject.toString();
//You cannot perform these UI operation on non-UI thread
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(message);
Log.e("JSON Input", message);
wr.flush();
wr.close();
conn.connect();
is = conn.getInputStream();
contentAsString = is.toString();
} catch (IOException e) {
Log.d("shit", "Shit");
} catch (JSONException e) {
Log.d("shit", "Shit");
} finally {
conn.disconnect();
}
//return response to onPostExecute()
return contentAsString;
}
#Override
protected void onPostExecute(String res){
//Do anything with response
}
}
}

Are you sure you are not running this in the main UI thread. Create a new thread or use AsyncTask to perform network operations.
public class BackgroundTask extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://disjunct-swabs.000webhostapp.com/testapp.php");
JSONObject postDataParams = new JSONObject();
postDataParams.put("id", "0");
postDataParams.put("balance", "666");
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) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
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();
}
}
In the above thread, you cannot declare, initialize or perform operation(setText) on any view, because they must happen on UI thread only. Put that in onPreExecute or onPostExecute methods
Now you cun run the code by
new BackgroundTask().execute();
Also add permission in manifest
<uses-permission android:name="android.permission.INTERNET" />
If you are using Android M or above, you must ask permission during runtime as well. This should be your goToNextLevel() method
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mLevelTextView.setText("Level " + (++mLevel));
mInterstitialAd = newInterstitialAd();
loadInterstitial();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.INTERNET
}, 10);
}
}
new BackgroundTask().execute();
}

Related

How to check if Referer is empty or not before downloading

I have this two URL
From this website https://wvw1.123movies.net/ I got this URL
https://s02.eplayvid.net/vids/mars.attacks.1996.720p.brrip.x264.yify.mp4
and from https://oceanofapk.com/ I got this URL
https://51-75-145-23.xyz/OceanofAPK.com/KSWEB_v3.963_[Pro_Mod_By_Stabiron].apk?md5=8RIbo_gkOkiR7c9XrpVDnQ&expires=1655617658
The first one requires Referer but the second one doesn't require Referer but will throws 403 error if I added Referer to the request.
Adding this to the first one will work
connection.addRequestProperty("Referer", url.toExternalForm());
but to the second one throws 403 forbidden error.
So my question is how can I check if the server requires Referer header request or not and based on that download the file.
Full Code
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.webkit.CookieManager;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Demo extends AppCompatActivity {
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
// declare the dialog as a member field of your activity
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(Demo.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(Demo.this);
downloadTask.execute("https://s02.eplayvid.net/vids/mars.attacks.1996.720p.brrip.x264.yify.mp4");
//downloadTask.execute("https://51-75-145-23.xyz/OceanofAPK.com/KSWEB_v3.963_[Pro_Mod_By_Stabiron].apk?md5=8RIbo_gkOkiR7c9XrpVDnQ&expires=1655617658");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true); //cancel the task
}
});
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Referer", url.toExternalForm());
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.61 Mobile Safari/537.36");
// Get the cookies for the current domain.
String cookiesString = CookieManager.getInstance().getCookie(url.toString());
// Only add the cookies if they are not null.
if (cookiesString != null) {
// Add the cookies to the header property.
connection.setRequestProperty("Cookie", cookiesString);
}
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/mars.attacks.1996.720p.brrip.x264.yify.mp4");
//output = new FileOutputStream("/sdcard/ksweb.apk");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) Demo.this.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
System.out.println(result);
}else {
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
}

Why Toast in this application does not show anything?

I wrote an application that connect to wamp server ( with a MySQl datatbase that one of its rows in table users have Username="pooriya" and Password="123")
This application checks if Username "pooriya" exist then Toast the password and if does not exist Toast "no user"
When i run this app on emulator , it should Toast "123", but
empty Toast is shown . Why ?
Even when i change the User to a not existing Username , like "poori" , again empty Toast is shown . Why ?
database name is "note_test_2_db"
And when i enter the address "http://127.0.0.1:8080/mysite1/index.php" in my browser , it shows "no user" , then i guess that the php file works correctly and the problem is in my android code .
Thanks
package com.example.GetDataFromServer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyActivity extends Activity {
public static String res = "";
Button btn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button);
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
}
});
}
}
package com.example.GetDataFromServer;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
* Created with IntelliJ IDEA.
* User: Farid
* Date: 3/15/19
* Time: 4:09 PM
* To change this template use File | Settings | File Templates.
*/
public class getdata extends AsyncTask {
private String Link = "";
private String User = "";
public getdata(String link, String user) {
Link = link;
User = user;
}
#Override
protected String doInBackground(Object... objects) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr= new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
MyActivity.res = sb.toString();
} catch (Exception e) {
}
return ""; //To change body of implemented methods use File | Settings | File Templates.
}
}
$con=mysql_connect("localhost","root","");
mysql_select_db("note_test_2_db",$con);
$user=$_POST['username'];
$sqlQ="select * from users where Username='$user'";
$result= mysql_Query($sqlQ);
$row=mysql_fetch_array($result);
if($row[0]){
print $row[1];
}
else{
print "no user";
}
mysql_close($con);
Problem: It seems your code to show Toast is incorrect.
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
}
});
When the first line is executed, the app will start the AsyncTask which connects to your server to get the response ("123" or "No User").
If you click on the button btn before the AsyncTask completed, at this time, the value of res is "", that why you always get empty Toast.
Solution: You can do the following steps
Step 1: Because getdata is a separate class, so you need to define an interface to pass data ("123" or "No User" or any value) back to MyActivity.
public interface OnDataListener {
void onData(String result);
}
Step 2: Modify getdata class
public class getdata extends AsyncTask<Object, Void, String> {
private String Link = "";
private String User = "";
private WeakReference<OnDataListener> mListener;
public getdata(String link, String user, OnDataListener listener) {
Link = link;
User = user;
mListener = new WeakReference<>(listener);
}
#Override
protected String doInBackground(Object... objects) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// This string will pass as param of onPostExecute method.
return sb.toString(); // Will return "123" or "No User" if there is no exception occurs.
} catch (Exception e) {
}
// If your app reach this line, it means there is an exception occurs, using a unique string for debugging.
// This string will pass as param of onPostExecute method
return "An exception has been caught!!!";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Pass the result back to MyActivity's onData method.
if (mListener != null && mListener.get() != null) {
mListener.get().onData(result);
}
}
}
Step 3: Let MyActivity implements OnDataListener interface.
public class MyActivity extends AppCompatActivity implements OnDataListener {
public static String res = "";
Button btn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button);
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya", this).execute();
// TODO: Comment-out this code
// btn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
// }
// });
}
#Override
public void onData(String result) {
// result is passed from the AsyncTask's onPostExecute method.
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
Note: Because you do not use any loading indicator while connecting to the server, so you need to wait a few seconds to see the Toast on the screen.
I solved the problem . I should use http://10.0.2.2:8080/mysite1/index.php instead http://127.0.0.1:8080/mysite1/index.php

package org.apache.http.client does not exist [duplicate]

This question already has answers here:
Android Cannot access org.apache.http.client.HttpClient
(2 answers)
Closed 7 years ago.
I am trying to check log in credentials , But I am getting these errors again and again , I have tried everything. I am new to android
Any kind of help will be appreciated. If there is other good way to implement same , want to know how to imply
Error
Error:(19, 30) error: package org.apache.http.client does not exist
Error:(15, 23) error: package org.apache.http does not exist
Error:(16, 23) error: package org.apache.http does not exist
Error:(17, 23) error: package org.apache.http does not exist
Error:(18, 30) error: package org.apache.http.client does not exist
Error:(20, 37) error: package org.apache.http.client.entity does not exist
Error:(21, 38) error: package org.apache.http.client.methods does not exist
Error:(22, 35) error: package org.apache.http.impl.client does not exist
Error:(23, 31) error: package org.apache.http.message does not exist
Error:(79, 22) error: cannot find symbol class NameValuePair
Error:(85, 49) error: cannot find symbol class DefaultHttpClient
Error:(86, 21) error: cannot find symbol class HttpPost
Error:(86, 45) error: cannot find symbol class HttpPost
Error:(88, 44) error: cannot find symbol class UrlEncodedFormEntity
Error:(90, 21) error: cannot find symbol class HttpResponse
Error:(92, 21) error: cannot find symbol class HttpEntity
Error:(105, 26) error: cannot find symbol class ClientProtocolException
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Error:(85, 21) error: cannot find symbol class HttpClient
Error:(81, 40) error: cannot find symbol class BasicNameValuePair
Error:(80, 40) error: cannot find symbol class BasicNameValuePair
Error:(79, 68) error: cannot find symbol class NameValuePair
MainActivity.java
package com.tarun.proxy_maar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://shaadi.web44.net/hello.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Add that to your build.gradle:
android {
useLibrary 'org.apache.http.legacy'
}
Or you use the HttpURLConnection class instead.
The DefaultHttpClient and NameValuePair classes were deprecated in API level 22, and removed in API level 23.
Google even took down the documentation for them.
When the documentation was still up, it recommended to switch to HttpUrlConnection for basic tasks such as this.
Here's a modified version of your AsyncTask that will work on API level 23:
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
String url = "http://shaadi.web44.net/hello.php";
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
sbParams = new StringBuilder();
try {
sbParams.append("name").append("=")
.append(URLEncoder.encode(uname, charset));
sbParams.append("&");
sbParams.append("password").append("=")
.append(URLEncoder.encode(pass, charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
//response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
return result.toString();
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
Full class code:
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
String url = "http://shaadi.web44.net/hello.php";
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
sbParams = new StringBuilder();
try {
sbParams.append("name").append("=")
.append(URLEncoder.encode(uname, charset));
sbParams.append("&");
sbParams.append("password").append("=")
.append(URLEncoder.encode(pass, charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
//response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
return result.toString();
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Application says: Unfortunately stopped. (on adding JsonObject from google)

I am trying to push data to a server after taking values from the accelerometer.
In that I am using JsonObject from google.
There seems to be some problem with this object. As soon as I put instantiate one object from this my application throws an error: Unfortunately appname has stopped.
My MainActivity code:
package com.example.accelerometerdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
public class MainActivity extends Activity implements SensorEventListener {
private static final String MSG_TAG_1 = "MainActivity";
private static final String MSG_TAG_2 = "place_holder";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2, test;
RelativeLayout layout;
int i = 0;
//For preparing file
String[] paramName = { "device_id", "timestamp", "sensor_type",
"sensor_value" };
String URLStr = "http://209.129.244.7/sensors";
java.util.Date date = new java.util.Date();
#Override
public final void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //refer layout file code below
//get the sensor service
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//get the accelerometer sensor
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//If sensor not available
if (mAccelerometer == null){
System.out.println("no temperature sensor");
}
//get layout
layout = (RelativeLayout)findViewById(R.id.relative);
//get textviews
title=(TextView)findViewById(R.id.name);
tv=(TextView)findViewById(R.id.xval);
tv1=(TextView)findViewById(R.id.yval);
tv2=(TextView)findViewById(R.id.zval);
test = (TextView)findViewById(R.id.testval);
}
#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;
}
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy)
{
// Do something here if sensor accuracy changes.
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
i++;
if (i < 5) {
getAccelerometer(event);
} else {
onPause();
}
}
}
public final void getAccelerometer(SensorEvent event)
{
// Many sensors return 3 values, one for each axis.
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
String t = "This is a test value";
//display values using TextView
title.setText(R.string.app_name);
tv.setText("X axis" +"\t\t"+x);
tv1.setText("Y axis" + "\t\t" +y);
tv2.setText("Z axis" +"\t\t" +z);
test.setText("Testing" +"\t\t" +event.values[2]);
JsonObject jo = new JsonObject();
try {
//formatting the file
jsonObject_x.put("sensor_value", 78);
jo.addProperty("device_id", "nexus_test_dev"); //Long type
jo.addProperty("timestamp", date.getTime()); //Long type
jo.addProperty("sensor_type", "Accelerometer_x"); //String type
jo.addProperty("sensor_value", 78); //Double type
//String[] paramName = { "device_id", "timestamp", "sensor_type", "sensor_value" };
//{"device_id":"test", "timestamp": 1373566899100, "temp": 123}
String[] paramVal = { "aeron_test_p", String.valueOf(date.getTime()),
"temp", "121" };
//Displaying readings in LOGCAT
for(String s : paramVal){
Log.d(MSG_TAG_1, s);
}
try {
httpPostSensorReading(URLStr, jo.toString());
Log.d(MSG_TAG_2, "Test");
} catch (Exception e) {e.printStackTrace();
}
} catch (JsonIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String httpPostSensorReading(String urlStr, String jsonString) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(jsonString);
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
#Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}
}
The moment I add this
JsonObject jo = new JsonObject();
The application throws an error "Unfortunately appname hsa stopped.
SOme issue with JsonObject. I used JSONObject then it was working fine.
Thanks,
I am sure you need to use not constructor for JsonObject, but JsonObjectBuilder to create JsonObject:
JsonObject jo = Json.createObjectBuilder()
.add("device_id", "nexus_test_dev")
.build();
Here is link on javadoc:
http://docs.oracle.com/javaee/7/api/javax/json/JsonObjectBuilder.html
Could not find class 'com.google.gson.JsonObject', referenced from method com.example.accelerometerdemo.MainActivity.getAccelerometer
You need to copy the gson.jar to your projects libs folder. Clean and build and t should work.
Note: Android's current build tools (Eclipse and command-line) expect that JARs are in a libs/ directory. It will automatically add those JARs to your compile-time build path

android-asyncTask keeps looping

Im kinda new in android development, Im trying to do a login process for app, i have successfully complete the process with http post method on a php script on my local host, however to make my login process nicer i decided use progressdialog to show when the authentication process runs but the progress keeps looping. Below is my code:
LoginActivity.java - login button:
opt = new HttpRequest();
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private boolean authResult = false;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
if(opt.loginAuth(txtUsername.getText().toString(), txtPassword.getText().toString())){
Log.i(Data.tagInfo,"Redirecting to mainpage");
opt.showToast(LoginActivity.this,"Login Successful");
startActivity(new Intent("com.example.MainActivity"));
}
else{
opt.showToast(LoginActivity.this,"Login Fail");
Log.i(Data.tagError,"Login Fail");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
btnLogin.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
});
HttpRequest.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.util.Log;
public class HttpRequest extends Operations {
public boolean loginAuth(String user , String pass){
//Log.i("Info",user+"|"+pass);
String folder = "mobileapp",
script = "/loginAuth_m-script.php",
fullpath = folder+script,
parameter = "username="+user+"&password="+pass,
result = "";
try {
JSONArray jArray = convertJSON(new SendRequest().execute(fullpath,parameter).get());
result = getSpecificJSONdata(jArray,"result");
Log.i(Data.tagInfo,"Login result:"+result);
if(result.equals(Data.success)){
Log.i(Data.tagInfo,"loginAuth() return true");
return true;
}
else{
Log.i(Data.tagInfo,"loginAuth() return false");
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i(Data.tagError,"Error:"+e.toString());
return false;
}
}
private class SendRequest extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg) {
// TODO Auto-generated method stub
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
try
{
url = new URL("http://"+Data.host+"/"+arg[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(arg[1]);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Log.i("Info","Server Response:"+response);
isr.close();
reader.close();
return response;
}
catch(IOException e)
{
Log.i("InfoError",e.toString());
return "";
// Error
}
}
}
}
Thanks alot in advance^^

Categories