i was trying to create an online apps. I would like to send a string from my apps to my PHP script, but it ended up with the php doesn't receive any string from my apps, which means the PhP will echo back NULL. I have been doing research online and searching for solution, but none of them worked.
Below is my MainActivity.java code:
package my.com.tutionathome.calvinlau.testserver;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b;
EditText et;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
et= (EditText)findViewById(R.id.EditText01);
tv= (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
Thread thread = new Thread()
{
#Override
public void run() {
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $"username" = $_POST['username'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
tv.setText("Response from PHP : " + response);
}
});
}catch(Exception e){
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
}
});
System.out.println("Exception : " + e.getMessage());
}
}
};
thread.start();
}
});
}
}
And my php code:
<?php
// put your code here
$hostname_localhost ="localhost";
$database_localhost ="android";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select Email, Username from tblmember where Username = '".$username."' AND Email = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($username == NULL){
echo "NULL";
}else{
echo $username;
}
?>
This is my Android Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.com.tutionathome.calvinlau.testserver">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
There are a bunch of libraries to facilitate this, saving many lines of code, i particularly suggest retrofit.
Try this Code.
AysncyTask
private class AysncyTask extends AsyncTask<Void,Void,Void>
{
private ProgressDialog regDialog=null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
regDialog=new ProgressDialog(this);
regDialog.setTitle(getResources().getString(R.string.app_name));
regDialog.setMessage(getResources().getString(R.string.app_pleasewait));
regDialog.setIndeterminate(true);
regDialog.setCancelable(true);
regDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
et.getText().toString().trim()));
postParameters.add(new BasicNameValuePair("password",
etpass.getText().toString().trim()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php",
postParameters);
res = response.toString();
return res;
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(3000);
// error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
}
} catch (Exception e) {
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(regDialog!=null)
{
regDialog.dismiss();
//do you code here you want
}
// do what u do
}
SimpleHttpClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpatch(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a project, and when I run it, then I press login button, my apps always force close, but if I launch my apps again, the login status is true.
and the message of error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.farid.starsrunway.login.LoginActivity$Masuk.onPostExecute(LoginActivity.java:126)
at com.farid.starsrunway.login.LoginActivity$Masuk.onPostExecute(LoginActivity.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:667)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6157)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.farid.starsrunway">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".login.LoginActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".login.RegisterActivity"
android:label="Register New User">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".login.LoginActivity" />
<intent-filter>
<action android:name="android.intent.action.DETAIL" />
<category android:name="android.intent.category.DETAIL" />
</intent-filter>
</activity>
<activity
android:name=".MainmenuActivity"
android:label="Menu Utama">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".login.LoginActivity" />
<intent-filter>
<action android:name="android.intent.action.DETAIL" />
<category android:name="android.intent.category.DETAIL" />
</intent-filter>
</activity>
</application>
</manifest>
this is SessionManager.java
package com.farid.starsrunway.login;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
#SuppressLint("CommitPrefEdits")
public class SessionManager {
// Shared Preferences
private SharedPreferences pref;
// Editor for Shared preferences
private Editor editor;
// Context
private Context _context;
// nama sharepreference
private static final String PREF_NAME = "Sesi";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
//public static final String KEY_NAME = "nama";
private static final String KEY_USER = "username";
// Constructor
public SessionManager(Context context){
this._context = context;
int PRIVATE_MODE = 0;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String user, String username){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
//editor.putString(KEY_NAME, name);
editor.putString(KEY_USER, username);
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
Intent i = new Intent(_context, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
//((Activity)_context).finish();
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
//user.put(KEY_NAME, pref.getString(KEY_NAME, null));
user.put(KEY_USER, pref.getString(KEY_USER, null));
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent i = new Intent(_context, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
this is LoginActivity.java
package com.farid.starsrunway.login;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.farid.starsrunway.Konfigurasi;
import com.farid.starsrunway.MainmenuActivity;
import com.farid.starsrunway.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.app.ProgressDialog;
import android.util.Log;
import com.farid.starsrunway.JSONParser;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
EditText EditUser, EditPass;
Button ButtonLogin, ButtonDaftar, ButtonCancel;
String url, success;
SessionManager session;
String st = "1";
String benar = "benar";
#Override
protected void onCreate(Bundle savedInstanceState) {
success = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
EditUser = findViewById(R.id.editUser);
EditPass = findViewById(R.id.editPass);
ButtonLogin = findViewById(R.id.buttonLogin);
ButtonCancel = findViewById(R.id.buttonCancel);
ButtonDaftar = findViewById(R.id.buttonDaftar);
ButtonLogin.setOnClickListener(this);
ButtonCancel.setOnClickListener(this);
ButtonDaftar.setOnClickListener(this);
}
public void login(){
String User = EditUser.getText().toString().trim();
String Pass = EditPass.getText().toString().trim();
url = Konfigurasi.URL_LOGIN + "username="
+ User + "&password="
+ Pass;
if (EditUser.getText().toString().trim().length() > 0 && EditPass.getText().toString().trim().length() > 0) {
new Masuk().execute();
} else {
Toast.makeText(getApplicationContext(), "Username/password masih kosong gan.!!", Toast.LENGTH_LONG).show();
}
}
public void Daftar(){
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
public void cancel(){
finish();
}
#SuppressLint("StaticFieldLeak")
public class Masuk extends AsyncTask<String, String, String> {
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Tunggu Bentar ya...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals(benar)) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
String user = c.getString("username").trim();
String pass = c.getString("password").trim();
session.createLoginSession(user, pass);
Log.e("ok", " ambil data");
}
} else {
Log.e("error", "tidak bisa ambil data 0");
}
} catch (Exception e) {
Log.e("error", "tidak bisa ambil data 1");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (success.equals(benar)) {
startActivity(new Intent(LoginActivity.this, MainmenuActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Username/password salah..!!", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == ButtonLogin){
login();
}
if (v == ButtonCancel){
cancel();
}
if (v == ButtonDaftar){
Daftar();
}
}
}
this is JSONParser.java
package com.farid.starsrunway;
import android.util.Log;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.List;
public class JSONParser {
static InputStream is = null;
private static JSONObject jObj = null;
private static String json = "";
// constructor
public JSONParser() {
//timeout = new Values().gettimeout();
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
HttpParams httpParameters = new BasicHttpParams();
int timeout = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException ste) {
Log.e("Timeout Exception: ", ste.toString());
} catch (ConnectTimeoutException e) {
Log.e("Timeout Exception: ", e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
this is konfigurasi.java
package com.farid.starsrunway;
public class Konfigurasi {
//Dibawah ini merupakan Pengalamatan dimana Lokasi Skrip CRUD PHP disimpan
//Pada tutorial Kali ini, karena kita membuat localhost maka alamatnya tertuju ke IP komputer
//dimana File PHP tersebut berada
//PENTING! JANGAN LUPA GANTI IP SESUAI DENGAN IP KOMPUTER DIMANA DATA PHP BERADA
private static final String BASE_URL = "http://runway.ikc.co.id/android/";
public static final String URL_READ = BASE_URL + "visit/read.php";
public static final String URL_INSERT = BASE_URL + "visit/create.php";
public static final String URL_UPDATE = BASE_URL + "visit/update.php";
public static final String URL_DELETE = BASE_URL + "visit/delete.php?id=";
public static final String URL_LOGIN = BASE_URL + "login/login.php?";
public static final String URL_REGISTER = BASE_URL + "login/register.php";
//Dibawah ini merupakan Kunci yang akan digunakan untuk mengirim permintaan ke Skrip PHP
public static final String KEY_ID = "id";
public static final String KEY_TANGGAL = "tanggal";
public static final String KEY_JAM = "jam"; //alamat itu variabel untuk alamat
public static final String KEY_LOC = "lokasi"; //lati itu variabel untuk latitude
public static final String KEY_KD_TOKO = "kodetoko"; //longi itu variabel untuk longitude
public static final String KEY_STATUS = "status";
public static final String KEY_KD_ASM = "kodeasm";
public static final String KEY_TYPE = "type";
public static final String KEY_USER = "username";
public static final String KEY_PASS = "password";
//JSON Tags
public static final String TAG_SUCCESS = "success";
public static final String TAG_VISIT = "visit";
public static final String TAG_ID = "id";
public static final String TAG_TANGGAL = "tanggal";
public static final String TAG_JAM = "jam";
public static final String TAG_KD_TOKO = "kodetoko";
public static final String TAG_LOC = "lokasi";
public static final String TAG_STATUS = "status";
public static final String TAG_KD_ASM = "kodeasm";
}
this is RequestHandler.java
package com.farid.starsrunway;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class RequestHandler {
//Metode Untuk mengirim httpPostRequest
//Metode ini mengambil 2 Argumen
//Metode Pertama adalah URL dari Skrip yang digunakan untuk mengirimkan permintaan
//Yang lainnya adalah HashMap dengan nilai pasangan nama yang berisi data yang akan dikirim dengan permintaan
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
//Membuat URL
URL url;
//Objek StringBuilder untuk menyimpan pesan diambil dari server
StringBuilder sb = new StringBuilder();
try {
//Inisialisasi URL
url = new URL(requestURL);
//Membuat Koneksi HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Konfigurasi koneksi
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Membuat Keluaran Stream
OutputStream os = conn.getOutputStream();
//Menulis Parameter Untuk Permintaan
//Kita menggunakan metode getPostDataString yang didefinisikan di bawah ini
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 br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public String sendGetRequest(String requestURL){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s).append("\n");
}
}catch(Exception ignored){
}
return sb.toString();
}
public String sendGetRequestParam(String requestURL, String id){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s).append("\n");
}
}catch(Exception ignored){
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
this is gradle:app
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.farid.starsrunway"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
this is login.php
<?php
include "koneksi.php";
$user = $_GET["username"];
$pas = $_GET["password"];
$pass = md5($pas);
$query = "SELECT * FROM User WHERE Username='$user' AND Password='$pass' ";
$hasil = mysqli_query($con, $query);
if (mysqli_num_rows($hasil) > 0) {
$response = array();
$response["login"] = array();
while ($data = mysqli_fetch_array($hasil)){
$login['Id'] = $data['Id'];
$login['Type'] = $data['Type'];
$login['Username'] = $data['Username'];
$login['Password'] = $data['Password'];
array_push($response["login"], $login);
}
$response["success"] = benar;
echo json_encode($response);
} else {
$response["success"] = salah;
$response["message"] = "Tidak ada data";
echo json_encode($response);
}
?>
can you help me, please.
I tried to resolve this problem 3 days ago, and I can't resolve it.
This is because in your LoginActivity.java, line 124, if (success.equals(benar)) results to a NullPointerException. Based on what I can understand from your code, if you change
success = null; to
success = "notbenar"; //or basically any value that is not null
in line 39, your problem should be solved.
Jacob is correct, success.equals() throws exception because it is null.
The same exception should have thrown in doInBackground, but you have a capture on it:
} catch (Exception e) {
Log.e("error", "tidak bisa ambil data 1");
}
Actually your log should have indicated success is null.
I believe you have forgotten the double quotes when assigning the value.
instead of using: $response["success"] = benar;
try this: $response["success"] = "benar";
modify this one as well,
$response["success"] = salah;
$response["success"] = "salah";
In this class I am sending request to server asynchronously by extending AsyncTask using HttpClient, I have created two custom classes one for Uploading and Downloading of Images from the server, and other for sending JSON Object and array. Beside this I'm also able to differentiate the requests using RequestTag
Can we also do the same using volley?
How can I upgrade to Volley from the HttpClient having same approach like in below class?
package com.creative.projectmanager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import org.apache.commons.logging.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
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 org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* server manager class. performs all server requests asynchronously
*/
public class ServerManager {
final private String SERVER_ADDRESS = "http://192.168.200.10/";
public void login(String email, String password, int requestTag) {
String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
HashMap<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
params.put("authenticate", "false");
android.util.Log.w("My App", email + " " + password + " " + requestTag);
AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
requestSender.execute();
}
public void downloadImage(String imageUrl, int imageSize, int requestTag) {
ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
imageDownloadTask.execute();
}
private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
private String url = "";
private HashMap<String, String> postParams = null;
private int requestTag;
private String errorMessage = "";
public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
this.url = url;
postParams = params;
this.requestTag = tag;
}
#Override
protected String doInBackground(Void... params) {
byte[] result;
String resultString = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
for (String key:postParams.keySet()
) {
nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
}
android.util.Log.w("My App",nameValuePairs.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
errorMessage = "ok";
result = EntityUtils.toByteArray(response.getEntity());
resultString = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
errorMessage = "Encoding is not supported";
}
catch (Exception e) {
errorMessage = "An error occurred";
}
return resultString;
}
#Override
protected void onPostExecute(String s) {
if (errorMessage.equals("ok")) {
sourceActivity.requestFinished(s, requestTag);
}
else
sourceActivity.requestFailed(errorMessage, requestTag);
}
}
private class ImageDownloadTask extends AsyncTask<String, String, String> {
private String imageUrl;
private int imageSize;
private int requestTag;
Bitmap image;
public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
this.imageUrl = imageUrl;
this.imageSize = imageSize;
this.requestTag = requestTag;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(imageUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
image = createScaledBitmapFromStream(inputStream, imageSize);
}
catch (Exception e){
//do nothing
}
return null;
}
#Override
protected void onPostExecute(String s) {
sourceActivity.imageDownloaded(image, requestTag);
}
protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
try {
BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
if (minimumDesiredBitmapSize > 0) {
BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
decodeBoundsOptions.inJustDecodeBounds = true;
bufferedInputStream.mark(32 * 1024);
BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
bufferedInputStream.reset();
int originalWidth = decodeBoundsOptions.outWidth;
int originalHeight = decodeBoundsOptions.outHeight;
decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
}
return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
}
catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedInputStream.close();
} catch (IOException ignored) {}
}
}
}
}
There are a lot of examples of how to make requests with Volley, so "upgrading" will mean rewriting your code in different way.
Volley, in my opinion is not the best library for HTTP calls, I would recommend you to try
http://square.github.io/retrofit/
for loading images use http://square.github.io/picasso/ or glide. These libraries will help you make you code cleaner whit out boilerplate stuff.
I have an application hosted on "heroku". It has this method you call it via a get and it will respond with a "Json code"
public static Result renderManga(int id) {
Manga m = Manga.find.byId(id);
if (m != null) {
return ok(Json.toJson(m));
} else
return null;
}
}
route file
GET /srvc/manga/:id controllers.Services.renderManga(id:Integer)
now my android code
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://boku-no-manga.herokuapp.com/srvc/manga/5"));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
EditText res = (EditText) findViewById(R.id.result);
res.setText(responseString);
Log.i("JSONmymanga",responseString);
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {}
I want to receive that JSON code sent by my play app and work with it in my android app.
Try this code,
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ServerTest extends Activity {
private String TAG = "test";
private String url = "https://boku-no-manga.herokuapp.com/srvc/manga/5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
}
}
}
Also make sure you have added this to manifest,
<uses-permission android:name="android.permission.INTERNET" />
I have an AsyncTask that currently shows a spinner dialog on login but it doesn't work very well from a user perspective it goes and gets everything then kind of spins into the second intent when it's done - it looks fine when you have a good signal but it works rubbish when the signal is bad or when it jumps from 3G to wifi mid sentence
so. what I want is a login page that works by showing a progressbar dialog on submit click and only once it's DONE jump to the 2nd intent
Here is what I have so far
package com.pprem.include;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Include_CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
then it is called by this in the actual activity
status="passed";
final class GetUserHttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
publishProgress(true);
try {
getUserPhpResponse = Include_CustomHttpClient.executeHttpPost(settings.getServer() + "getUser.php", postParameters);
return getUserPhpResponse;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String getUserPhpResponse) {
publishProgress(false);
//result = result.replaceAll("\\s+","");
settings.setFullname(getUserPhpResponse);
JSONObject jObject;
try {
jObject = new JSONObject(getUserPhpResponse);
settings.setFullname(jObject.getString("fullname"));
settings.setAdministrator(jObject.getString("administrator"));
if (status=="passed"){
//start the second Activity
gotofrmListSchema.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
gotofrmListSchema.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(gotofrmListSchema);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
new GetUserHttpTask().execute();
I think you need something like this
private class RemoteTask extends AsyncTask<Object, Void, String > {
private ProgressDialog dialog;
private Context context;
private RemoteTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage(getResources().getString(R.string.loading));
dialog.show();
}
#Override
protected String doInBackground(Object... objects) {
return client.executeGet(objects[0]);
}
#Override
protected void onPostExecute(String result) {
if (dialog.isShowing())
dialog.dismiss();
...
//start new activity here
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange NetworkOnMainThreadException in Android app?
Trying To Upload To Dropbox: NetworkOnMainThreadException?
I have used the below code for reading HTML contents from a url. This works perfectly for 2.3.3 but when I try to run the same code it doesn't work for ICS.
I am trying to append these html contents on to a edittext. But it always remains empty when I run the code on ICS. What may be the problem?
public class Quiz1Activity extends Activity {
private static BufferedReader reader = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText ed = (EditText) findViewById(R.id.editText1);
try {
ed.append(getStringFromUrl("http://www.google.com"));
//getInputStreamFromUrl("").close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}
public static String getStringFromUrl(String url) throws IOException{
reader = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
}
Like #Vipul Shah said you have to move getInputStreamFromUrl() into another thread use Async Task, this is work on ICS:
package com.home.anas;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.EditText;
public class WebPageContentActivity extends Activity {
private EditText ed;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText) findViewById(R.id.editText1);
readWebpage();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
ed.setText(result);
}
}
public void readWebpage() {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.google.com" });
}
}
But it always remains empty when I run the code on ICS. What may be the problem?
Issue is ICS don't allow you do asynchronous task on main thread so move your asynchronous into new thread.
You should move following code in seperate thread.
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}