Application Crashed while trying to executing httppost - java

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.

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();"

Getting a NullPointerException error trying to connect a MySQL database to android

I know there are a lot of questions asked like this but I've looked at them all and none of the answers have worked for me.
Here is my java class
public class AllBugsActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> bugsList;
private static String url_all_bugs = "http://10.0.2.2/FinalYearProject/FYPFinal/android_connect/get_all_bugs.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_BUGS = "bugs";
private static final String TAG_BID = "bid";
private static final String TAG_NAME = "name";
JSONArray bugs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_bugs);
bugsList = new ArrayList<HashMap<String, String>>();
new LoadAllBugs().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bid = ((TextView) view.findViewById(R.id.bid)).getText()
.toString();
Intent in = new Intent(getApplicationContext(),
EditBugActivity.class);
in.putExtra(TAG_BID, bid);
startActivityForResult(in, 100);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllBugs extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllBugsActivity.this);
pDialog.setMessage("Loading bugs. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_bugs, "GET", params);
Log.d("All Bugs: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
bugs = json.getJSONArray(TAG_BUGS);
for (int i = 0; i < bugs.length(); i++) {
JSONObject c = bugs.getJSONObject(i);
String id = c.getString(TAG_BID);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_BID, id);
map.put(TAG_NAME, name);
bugsList.add(map);
}
} else {
Intent i = new Intent(getApplicationContext(),
NewBugActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
AllBugsActivity.this, bugsList,
R.layout.list_bug, new String[] { TAG_BID,
TAG_NAME},
new int[] { R.id.bid, R.id.name });
setListAdapter(adapter);
}
});
}
}
}
Heres my JSONParser class
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;
}
}
Heres the error im getting
03-21 17:06:15.158 1266-1280/com.example.neil.fypy4 E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:98)
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:856)
03-21 17:06:15.511 1266-1266/com.example.neil.fypy4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-21 17:06:16.008 1266-1266/com.example.neil.fypy4 E/WindowManager﹕ Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41cd1748 that was originally added here
android.view.WindowLeaked: Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41cd1748 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.onPreExecute(AllBugsActivity.java:92)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.example.neil.fypy4.AllBugsActivity.onCreate(AllBugsActivity.java:50)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
My php class
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM bugs") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["bugs"] = array();
while ($row = mysql_fetch_array($result)) {
$bug = array();
$bug["bid"] = $row["bid"];
$bug["name"] = $row["name"];
$bug["severity"] = $row["severity"];
$bug["description"] = $row["description"];
$bug["created_at"] = $row["created_at"];
$bug["updated_at"] = $row["updated_at"];
array_push($response["bugs"], $bug);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No bugs found";
echo json_encode($response);
}
?>
Any help would be greatly appreciated.
So in your stack trace, it'll show you line numbers: from this you can triangulate in your code where the NPE is coming from. Since you don't provide line numbers here, I'm going to take a guess that int success = json.getInt(TAG_SUCCESS); is causing the NPE. The reason is that it's the first possibly null object in doInBackground(...)--if you look at the JSONParser class, you return jObj which is a field member that is initialized to null, and only set if an error did not occur. That is, you do not check in doInBackground(...) whether JSONObject json returns null or not from = jParser.makeHttpRequest(url_all_bugs, "GET", params); instead relying on the TAG_SUCCESS. But this is a chicken and egg problem, since if it fails it can be null and there is no tag to check for success!
Anyways, my advice is to add if (json != null) before the try/catch in doInBackground(...). You'll probably find your JSONParser class is failing to parse correctly. You can use the line numbers from the stack trace to pinpoint where the problem is coming from, or just use the debugger and step through your code execution.
On a side note, you can make public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) a static method since the variables
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
don't need to be class scoped (and they are already static!). Just make them method scope and have a convenient static method call to parse your json.
A final comment: you don't need to call runOnUiThread(...) from onPostExecute(...) because onPostExecute(...) runs on the UI thread for every Async task. That's simply how Async task works.

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?

deciphering crash report from Google Play

I am receiving a crash report but it doesn't make sense to me. Says text may not be null. It works on any device I test with but somehow it is crashing for a few people. Latest one reported using a Galaxy Indulge (SCH-R910). Here is the report
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at java.lang.Thread.run(Thread.java:1096)
Caused by: java.lang.IllegalArgumentException: Text may not be null
at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:94)
at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:113)
at com.pff.photosfromfriends.UploadPicture$uploadthephoto.doInBackground(UploadPicture.java:313)
at com.pff.photosfromfriends.UploadPicture$uploadthephoto.doInBackground(UploadPicture.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 4 more
And here is my code for the upload
class uploadthephoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadPicture.this);
pDialog.setMessage("Uploading Picture");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(POST_COMMNT_URL);
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(theimagepath);
cbFile = new FileBody(file, "image/jpeg");
entity.addPart("username", new StringBody(username,
Charset.forName("UTF-8")));
entity.addPart("name", new StringBody(name,
Charset.forName("UTF-8")));
entity.addPart("album", new StringBody(spinselected, Charset.forName("UTF-8")));
entity.addPart("picture", cbFile);
post.setEntity(entity);
HttpResponse response1 = client.execute(post);
HttpEntity resEntity = response1.getEntity();
String Response = EntityUtils.toString(resEntity);
Log.d("Response", Response);
json = new JSONObject(Response);
success_number = json.getInt("success");
if (success_number == 1) { // picture added!
return json.getString("message");
} else {
Log.d("Login Failure!", json.getString(message));
return json.getString("message");
}
} catch (IOException e) {
Log.e("asdf", e.getMessage(), e);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(UploadPicture.this, file_url, Toast.LENGTH_LONG)
.show();
}
}
}
// Username is from SharedPreferences
// Name is from SharedPreferences
// Album is from a Spinner
// Picture is chosen from their gallery
Any idea why it would throw this error on some devices? Thank you.
It's this line:
entity.addPart("album", new StringBody(spinselected, Charset.forName("UTF-8")));
Apparently spinselected is null and StringBody throws an error if it is constructed with a null parameter.
Caused by: java.lang.IllegalArgumentException: Text may not be null
at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:94)

Error NullPointerException: lock == null

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

Categories