Error NullPointerException: lock == null - java

Can anyone help me with this error please, Select Values from MySQL Database to Android when i run app and search for ID, It always said (Invalid IP Address)...
I have a PHP file on my web server that connects to a WampServer database and retrieves values that are returned to Android app..
String id
String name;
InputStream is=null;
String result=null;
String line;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
Button select=(Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
id=e_id.getText().toString();
select();
}
});
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/test/select.php");
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);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
LogCat Error:
11-17 02:40:58.059: E/Fail 1(1073): android.os.NetworkOnMainThreadException
11-17 02:40:58.079: E/Fail 2(1073): java.lang.NullPointerException: lock == null
11-17 02:40:58.079: E/Fail 3(1073): java.lang.NullPointerException
any help appreciated...

E/Fail 1(1073): android.os.NetworkOnMainThreadException
This error is raised because you run your network connectivity calls (like httpclient) on your main Activity's thread. To get rid of that you need to use another thread for these calls. The easy way to do so would be to use the Async Task

Related

How can I connect to MySQL database with android (PHP)?

I have tried almost all the code that have been encountered about this issue.
I leave sample code below.
//select.php
<?php
$host='127.0.0.1';
$uname='root';
$pwd='';
$db="android";
$id=$_REQUEST['id'];
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
$sqlString = "select * from sample where id='$id' ";
$rs = mysql_query($sqlString);
if($rs){
while($objRs = mysql_fetch_assoc($rs)){
$output[] = $objRs; }
echo json_encode($output); }
mysql_close($con);
?>
//Main Activity
#Override
public void onClick(View v) {
id=e_id.getText().toString();
select();
}
});
}
public void select() {
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
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);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
} }}
I wrote this to.
<uses-permission android:name="android.permission.INTERNET"/>
//logcat
E/Fail 1: android.os.NetworkOnMainThreadException
E/Fail 2: java.lang.NullPointerException: lock == null
E/Fail 3: java.lang.NullPointerException
When I try to run the application I get the INVALID IP ADDRESS error.
I need some suggestions. What should I try to connect to MySQL database with android (PHP)?
Exception clearly showing that you are calling network operation on main thread that's why it is not working . Use async task for network operation and then it will work. From api level 11 android restricted network operations on main thread and if do this it will throw an error network on main thread exception. And you are getting the same exception.
#Developer_vaibhav I tried the way you said and I got the error again.
mainactivity.class
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://10.0.2.2/login.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, Main2Activity.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);
}
#user2508811 I used mysqli.
//login.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','root1234');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from users where username='$username' and
password='$password'";
$res = mysqli_query($con,$sql);
$check = mysqli_fetch_array($res);
if(isset($check)){
echo 'success';
}else{
echo 'failure';
}
mysqli_close($con);
?>
//logcat
FATAL EXCEPTION: main
java.lang.NullPointerException
MainActivity$1LoginAsync.onPostExecute(MainActivity.java:118)
MainActivity$1LoginAsync.onPostExecute(MainActivity.java:64)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5319)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
I run the application on the emulator and when I click on the button I get the error that stopped the application.
Class inside method? OMG. Make asynctask in isolated .java file and call "new LoginAsync().execute();"

Application Crashed while trying to executing httppost

i do sending request for json to server and receiving it with Asyntask , and i do executing httppost in doInBackground like this :
HttpResponse httpResponse = httpClient.execute(httpPost);
and if i disable internet connection while waiting for response from server, the application will be crashed! the problem is i don't know how to handle this exception (RuntimeException)
and ofcurse i handle these exceptions in my application :
ConnectionTimeoutException, SocketTimeoutException , NetworkOnMainThreadException , IllegalStateException , IOException,
UnsupportedEncodingException , ClientProtocolException
public class GetJSON extends AsyncTask<String, Void, String> {
String username;
String password;
Context context;
ArrayList<NameValuePair> valuesForServer =new ArrayList<NameValuePair>();
InputStream inputStream = null;
String result = "";
public GetJSON(Context context,String username, String password){
this.username=username;
this.password=password;
this.context=context;
valuesForServer.add(new BasicNameValuePair("api_key", "teroapi_php_java_1395"));
valuesForServer.add(new BasicNameValuePair("api_function", "login"));
valuesForServer.add(new BasicNameValuePair("username",this.username));
valuesForServer.add(new BasicNameValuePair("password",this.password));
}
#Override
protected String doInBackground(String... urls) {
try {
String url=urls[0];
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(valuesForServer));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
// Read content & Log
inputStream = httpEntity.getContent();
}else{
return null;
}
}catch(ConnectTimeoutException e5){
Toast.makeText(this.context, e5 + "", Toast.LENGTH_SHORT).show();
e5.printStackTrace();
return null;
}catch (NetworkOnMainThreadException e7){
Toast.makeText(this.context, e7 + "", Toast.LENGTH_SHORT).show();
e7.printStackTrace();
return null;
} catch(SocketTimeoutException e6){
Toast.makeText(this.context, e6 + "", Toast.LENGTH_SHORT).show();
e6.printStackTrace();
return null;
} catch (UnsupportedEncodingException e1) {
Toast.makeText(this.context, e1 + "", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
return null;
} catch (ClientProtocolException e2) {
Toast.makeText(this.context,e2+"",Toast.LENGTH_SHORT).show();
e2.printStackTrace();
return null;
} catch (IllegalStateException e3) {
Toast.makeText(this.context,e3+"",Toast.LENGTH_SHORT).show();
e3.printStackTrace();
return null;
} catch (IOException e4) {
Toast.makeText(this.context,e4+"",Toast.LENGTH_SHORT).show();
e4.printStackTrace();
return null;
}
// Convert response to string using String Builder
if(inputStream!=null) {
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Toast.makeText(this.context, e + "", Toast.LENGTH_SHORT).show();
return null;
}
}else {
return null;
}
return result;
}
#Override
public void onPostExecute(String result) {
if (result != null) {
MainActivity.analizeData(result);
if (MainActivity.success.equals("1")) {
MainActivity.teamsFragment.parseJSON();
MainActivity.projectsFragment.parseJSON();
MainActivity.dutiesFragment.parseJSON();
insertToDb(result);
try {
Picasso.with(context)
.load("http://teroject.com/upload/avatars/" + MainActivity.information.getString("profilepicurl") + ".jpg")
.error(R.drawable.avatar)
.into(MainActivity.navProfilePic);
} catch (JSONException e) {
Toast.makeText(this.context,e+"",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (MainActivity.success.equals("0")) {
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
Toast.makeText(context, "لطفا مجددا وارد شوید",
Toast.LENGTH_LONG).show();
((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
((Activity) context).finish();
SharedPreferences sharedPreferences = context.getSharedPreferences(TeroSession.TEROPREFS, context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
deleteFromDb();
}
}else {
Toast.makeText(this.context,"مشکلی در برقراری ارتباط بوجود آمده \n" +
"لطفا مجددا تلاش کنید",Toast.LENGTH_LONG).show();
}
}
}
my logcat :
07-24 02:52:27.591 3601-3723/com.teroject.teroject E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.teroject.teroject, PID: 3601
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:353)
at android.widget.Toast.<init>(Toast.java:108)
at android.widget.Toast.makeText(Toast.java:267)
at com.teroject.teroject.GetJSON.doInBackground(GetJSON.java:116)
at com.teroject.teroject.GetJSON.doInBackground(GetJSON.java:48)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 
thanks alot for giving your time!
This basically means that you cannot make Toasts (or do any other UI modification) from the background thread, but rather the UI thread. There are two ways of fixing this:
Convert each and every Toast to Log.i("some tag", e + "") since you're using Toasts for catching the errors and Log is a way better way do to that. These Logs will appear in your Android monitor (and you can search through them with CTRL+F)
You could also use Activity.runOnUiThread() and post the Toasts this way, which would be a worse choice given that you do not really need them, you're just using them for debugging.

Send json string to server

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().

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference [duplicate]

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?

JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I tried hard to search the solution but I still not manage to solve it. Kindly help. Here my java code : -
public class MainActivity extends Activity {
String project_id;
String id;
InputStream is=null;
String result=null;
String line=null;
int code = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id =(EditText) findViewById(R.id.editText1);
final EditText e_prjId =(EditText) findViewById(R.id.editText2);
Button insert =(Button) findViewById(R.id.button1);
id = e_id.getText().toString();
project_id = e_prjId.getText().toString();
insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
}
public void insert() {
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id));
new Thread(new Runnable() {
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php");
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 {
Log.i("tagconvertstr", "["+result+"]");
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
}
}
}).start();
}
php:-
<?php
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$ID=$_REQUEST['ID'];
$Project_Id=$_REQUEST['Project_Id'];
$flag['code']=0;
if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')"))
{
$flag['code']=1;
}
echo(json_encode($flag));
?>
I really no idea that what is the reason I keep receive error message from JSON exception error. Really appreciate somemore can help me.
Thanks
Be careful, PHP associative array are case sensitive
You are sending id:
nameValuePairs.add(new BasicNameValuePair("id",id));
which is not equal to ID
In addition to that mistake, you dont check the data in your php script, I rewrote it for you:
$data = array();
if(isset($_POST['id'], $_POST['Project_Id']){
$id=$_POST['id'];
$project_id=$_POST['Project_Id'];
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)'))
$success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id));
if($success){
$data['code'] = 1;
$data['msg'] = 'INSERT successful';
}else{
$data['code'] = 0;
$data['msg'] = 'INSERT Failed';
}
}else{
$data['code'] = 0;
$data['msg'] = 'values are not set';
}
echo(json_encode($data));

Categories