My client type is android and the language is Java.
This class connects to the server and gets the output stream to the connected server.
class ConnectToServer extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{
try {
socket = new Socket(ip,port);
output = new DataOutputStream(socket.getOutputStream());
Log.d(TAG, "Connected To Server!");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
class SendToServer extends AsyncTask<Void, Void, Void>
{
//Our Json object
JSONObject obj;// = new JSONObject();
//this class is called when the login button is pressed, it sends the username and password as arguments
public SendToServer(String username, String password)
{
//instantiate the new object
obj = new JSONObject();
try {
//create the first field Type
obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request
obj.put("username", username); //our server will get username
obj.put("password",password); //our server will get password
} catch (JSONException e) {
e.printStackTrace(); //if we get problems let the developer know
}
}
#Override
protected Void doInBackground(Void... params)
{
String jsonText = obj.toString(); //convert our json object into a string
byte[] b =jsonText.getBytes(Charset.forName("UTF-8")); //convert our json object into a byte array
try {
output.writeInt(b.length); // write length of the message
output.write(b); // write the message
output.flush(); //flush - empties the pipe
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
The purpose of this code is to send the server the users credentials.
In this C# Server
private void serverClient()
{
while(true)
{
int len = ns.ReadByte(); //read how much data
if (len == 0) //if this == 0 this means client has quit the program
break; //break out of loop and remove client from array list
if (len > 0) //we have a message
{
//read mess
byte[] message = new byte[len]; //create byte array
ns.Read(message, 0, message.Length); //read into the message byte array
string text = Encoding.ASCII.GetString(message, 0, len);
string text1 = Encoding.UTF8.GetString(message, 0, len); //build string from byte array up to how much data we got.
Console.WriteLine(text1);
}
}
removeClients();
}
So the Android client will send the credentials, but when the SendToServer class is called, the client disconnects from the server.
How can I send a Json string to my C# server so it can then read the string and serialize it into an object, depending on the fields.
private void updateDataToServer() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("score", score));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_update);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
/*
* Toast.makeText(getBaseContext(), "Update Successfully",
* Toast.LENGTH_SHORT).show();
*/
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
class PostDataToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
* pDialog = new ProgressDialog(MainActivity.this);
* pDialog.setMessage("Please wait..."); pDialog.show();
*/
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_create_product);
try {
name = edt_name.getText().toString();
score = edt_score.getText().toString();
quocgia = edt_quocgia.getText().toString();
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("score", score));
nameValuePairs.add(new BasicNameValuePair("quocgia", quocgia));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
#Override
protected void onPostExecute(String s) {
/*
* if (pDialog.isShowing()) { pDialog.dismiss();
* Toast.makeText(getApplication(), "Complete",
* Toast.LENGTH_LONG).show(); }
*/
}
}
Hope it helps you
You're reading lines but you aren't writing lines. Add a line terminator to the message being sent, or use println() instead of write().
Related
I'm using AsyncTask to insert, update and delete data from database. I used this code to insert, update, delete and it works fine. But when I want to use select, and show the data at EditText, I can't get the value from doInBackground() to the onPostExecute() and it shows nothing.
Here's my code :
MenuUtama.java
public class MenuUtama extends Activity {
/** Called when the activity is first created. */
private TextView nama_user;
private String nm_user = "";
private EditText kode, nama, harga, deskripsi;
private Button insert, update, delete, cek;
private String kode1, nama1, harga1, deskripsi1;
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
kode = (EditText) findViewById(R.id.editKode);
nama = (EditText) findViewById(R.id.editNama);
harga = (EditText) findViewById(R.id.editHarga);
deskripsi = (EditText) findViewById(R.id.editDes);
cek = (Button) findViewById(R.id.btnCek);
insert = (Button) findViewById(R.id.buttonInsert);
update = (Button) findViewById(R.id.buttonUpdate);
delete = (Button) findViewById(R.id.buttonDelete);
nama_user = (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
nm_user = i.getStringExtra("nama_user");
nama_user.setText(nm_user);
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=insert&kd=" + ko + "&nm=" + n + "&hrg=" + hr + "&deskripsi=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=update&kd=" + ko + "&nm=" + n + "&hrg=" +hr+ "&des=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=delete&kd=" + kode1;
new CRUD().execute(url);
}
});
cek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=read&kd="+kode1;
new CRUD().execute(url);
}
});
}
public class CRUD extends AsyncTask<String, String, String> {
String success;
String kode_d, nama_d, harga_d, des_d;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(params[0]);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
kode_d = c.getString("kd");
nama_d = c.getString("nm");
harga_d = c.getString("hrg");
des_d = c.getString("deskripsi");
}
}
else {
Log.e("erro", "tidak bisa ambil data 0");
}
}
catch (Exception e) {
// TODO: handle exception
Log.e("erro", "tidak bisa ambil data 1");
}
return kode_d;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
kode.setText(kode_d);
nama.setText(nama_d);
harga.setText(harga_d);
deskripsi.setText(des_d);
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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 + "\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;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
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();
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 (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
}
It is because you don't return any value from the doInBackground() (always return null) and you are not using the 'string' in the onPostExecute(String result) formal parameter. Garbage-In-Garbage-Out
your doInBackground() returns just a string return kode_d; and then in your onPostExecute(String result) (which expects a String) you use the kode_d which is null.
If you want all of those values to be returned create an ArrayList(), return it at the end doInBackground() and get it in onPostExecute(ArrayList result) with an iteration and pass it to you textviews.
Even better create an object and add the values to each field. Your fields are the kode_d, nama_d, harga_d, des_d
this is what the onPostExecute does
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.
* To better support testing frameworks, it is recommended that this be
* written to tolerate direct execution as part of the execute() call.
* The default version does nothing.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param result The result of the operation computed by {#link #doInBackground}.
*
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/
I am trying to connect my Android Application with mySQL. I am getting error in LogCat.
You can find my complete code here https://github.com/rraj56801/php-connection
I am concerning only on getting all product here.
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
JSONParser code here:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
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(new BasicHttpParams());
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://127.0.0.1");
try{
// Execute the request in the client
HttpResponse httpResponse = httpclient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
}catch(Exception e){
Log.d("Error",e.toString());
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
LogCat here:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'int org.json.JSONObject.getInt(java.lang.String)' on a null
object reference
at
com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:134)
at
com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
you are having problem in this line.
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
your json object is not getting value hence remains null. and letter you are trying to access a method of null object so the error occurs. check you url
or else check value before using
if(json != null)
{
try
{
int success = json.getInt(TAG_SUCCESS);
...
...
...
}
}
I'm trying to check the username/psw on my phpmyadmin database
but I can't figure out the problem.
The logcat gives me this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
Java code:
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
private String password="";
private String userName="";
JSONParser jsonParser = new JSONParser();
// url to create new product
private static String url_login = "http://localhost/android_connect/get_login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
Button btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
userName=editTextUserName.getText().toString();
password=editTextPassword.getText().toString();
new LoginUser().execute();
}
});
dialog.show();
}
class LoginUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Verificoo NomeUtente & Password ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking login
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("use_username", userName));
params.add(new BasicNameValuePair("use_psw", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS)
if (success == 1) {
//blablabla
} else {
Intent intent = getIntent();
finish();
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
#miselking
here the class JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// 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 {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
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();
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 (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
check json is not null
if(json!=null){do something}
Error at this line
httpPost.setEntity(new UrlEncodedFormEntity(params));
Use this line
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
and also in GET method use HTTP.UTF_8 instead of "utf-8"
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm Getting this error when runtime my project.
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
at com.example.arhen.tugasrplii.Register$InputData.onPostExecute(Register.java:100)
This is full log :
03-05 03:22:02.822 2575-2575/com.example.arhen.tugasrplii E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.arhen.tugasrplii, PID: 2575
**java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.arhen.tugasrplii.Register$InputData.onPostExecute(Register.java:100)**
at com.example.arhen.tugasrplii.Register$InputData.onPostExecute(Register.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This is my full code on Register.java :
/** * Created by arhen on 05/03/15. */
public class Register extends Activity{
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText first_name,last_name,email,username,password;
private static String url = "http://127.0.0.1/login/register.php";
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
register = (Button)findViewById(R.id.btn_register);
first_name = (EditText)findViewById(R.id.fld_first);
last_name = (EditText)findViewById(R.id.fld_last);
email = (EditText)findViewById(R.id.fld_email);
username = (EditText)findViewById(R.id.fld_username);
password = (EditText)findViewById(R.id.fld_pwd);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new InputData().execute();
}
});
}
public class InputData extends AsyncTask<String, String, String>{
String success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Registering Account...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String strfirst_name = first_name.getText().toString();
String strlast_name = last_name.getText().toString();
String stremail = email.getText().toString();
String strusername = username.getText().toString();
String strpassword = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name",strfirst_name));
params.add(new BasicNameValuePair("last_name",strlast_name));
params.add(new BasicNameValuePair("email",stremail));
params.add(new BasicNameValuePair("username",strusername));
params.add(new BasicNameValuePair("password",strpassword));
JSONObject json =
jsonParser.makeHttpRequest(url,
"POST", params);
try {
success = json.getString("success");
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if (success.equals("1")) {
Toast.makeText(getApplicationContext(),"Registration Succesfully",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Registration Failed",Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onBackPressed(){
Intent i = new Intent(getApplicationContext(),Login.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} }
i thought this error from JSONParser.java, .. this the code :
/**
* Created by arhen on 04/03/15.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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 + "\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;
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new
DefaultHttpClient();
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();
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 (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +
e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
this my register.php code:
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$username = $_POST['username'];
$pwd = $_POST['password'];
include 'koneksi.php';
$namaTabel = "akun";
header('Content-Type:text/xml');
$query = "INSERT INTO $namaTabel VALUES('','$first_name','$last_name','$email','$username','$pwd')";
$hasil = mysql_query($query);
if($hasil)
{
$response["success"] = "1";
$response["message"] = "Data has Input";
echo json_encode($response);
}
else
{$response["success"] = "0";
$response["message"] = "Upss, Something Happens! Try again";
// echoing JSON response
echo json_encode($response);
}
?>
I have seen this post :
What is a NullPointerException, and how do I fix it?
and I'm try to give success a string like :
String success ="";
But it didnt Works.. it give this statement error has activated on my code :
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
I have no idea. Pls Help ..
thanks So Much ...
Looks like this line might be returning null, if String success = "" didn't work:
success = json.getString("success");
Have you inspected the JSON that you are parsing and verified that the "success" field is where you expect and properly formatted?
I'm passing two strings between two activities and for some strange reason, the strings aren't being passed. I've done all the correct protocols and nothing seems to work, despite tinkering around with the code for several hours, I'm sure it's an simple solution, but I have no clue, what's so ever.
1st Class:
public class LogIn extends Activity implements OnClickListener {
Button ok, back, exit;
TextView result;
EditText pword;
String password;
EditText uname;
String username;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
//create bracket.
public void postLoginData() {
uname = (EditText) findViewById(R.id.txt_username);
uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
pword.getText().toString();
Bundle basket = new Bundle();
basket.putString("keypass", password);
basket.putString("keyuname", username);
Intent a = new Intent(LogIn.this, ChatService.class );
a.putExtras(basket);
startActivity(a);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(Login 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(Login2)", "TRUE");
result.setText("Login successful");
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
}else {
Log.w("HttpPost(Login(3)", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here
2nd class:
public class ChatService extends ListActivity {
/** Called when the activity is first created. */
BufferedReader in = null;
String data = null;
List headlines;
List links;
String GotPass;
String GotUname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get strings
Bundle gotData = getIntent().getExtras();
if(gotData !=null) {
GotPass = gotData.getString("keypass");
GotUname = gotData.getString("keyuname");
try {
//listview method
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
CheckLogin();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void CheckLogin() throws UnsupportedEncodingException {
// posts login data from "LogIn" class
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", GotUname));
nameValuePairs.add(new BasicNameValuePair("password", GotPass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(ChatService 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(ChatService 2)", "TRUE");
// make toast if str.equals("True")
Toast.makeText(getApplicationContext(), "Yayayaya, loged in", Toast.LENGTH_LONG );
}else {
Log.w("HttpPost(ChatService 3", "FALSE");
Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void ContactsandIm() throws URISyntaxException,
ClientProtocolException, IOException {
headlines = new ArrayList();
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l ="";
String nl ="";
while ((l =in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
if(data.contains("null"));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
// end bracket for "ContactsandIm"
}
Try this way.
Intent a = new Intent(context, MyActivity.class);
a.putExtra("String1", "Hello World");
context.startActivity(a);
and
Bundle extras = getIntent().getExtras();
String s1 = extras.getString("String1");
You should add both 2 activity in Mainfest.xml file
Check have you register your activity in manifest file.