deciphering crash report from Google Play - java

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)

Related

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.

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.

Error parsing data org.json.JSONException: End of input at character 0 of - LoginActivity

I am developing an android application which requires user to login, when i run the LoginActivity it gives me a json parser error, i think my php code is fine but i need another pair of eyes to help me find the bug in my code, thanks
Login Activity
public class LoginActivity extends Activity {
Button btnLogin;
EditText inputMobile;
EditText inputCountry;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_MOBILE = "mobile";
private static String KEY_COUNTRY = "country";
private static String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputMobile = (EditText) findViewById(R.id.phone);
inputCountry = (EditText) findViewById(R.id.country);
btnLogin = (Button) findViewById(R.id.login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((!inputMobile.getText().toString().equals(""))
&& (!inputCountry.getText().toString().equals(""))) {
NetAsync(view);
} else if ((!inputMobile.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),
"Mobile field empty", Toast.LENGTH_SHORT).show();
} else if ((!!inputCountry.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),
"Country field empty", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Mobile and Country field are empty",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String, String, Boolean> {
private ProgressDialog nDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection
* by trying Google.
**/
#Override
protected Boolean doInBackground(String... args) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th) {
if (th == true) {
nDialog.dismiss();
new ProcessLogin().execute();
} else {
nDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Error in Network Connection",
Toast.LENGTH_SHORT).show();
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String mobile, country;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputMobile = (EditText) findViewById(R.id.phone);
inputCountry = (EditText) findViewById(R.id.country);
mobile = inputMobile.getText().toString();
country = inputCountry.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(mobile, country);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME),
json_user.getString(KEY_MOBILE),
json_user.getString(KEY_COUNTRY),
json_user.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
/**
* If JSON array details are stored in SQlite it
* launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(),
MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
} else {
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect mobile/country",
Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view) {
new NetCheck().execute();
}
}
PHP code
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// Get tag
$tag = $_POST['tag'];
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$mobile = $_POST['mobile'];
$country = $_POST['country'];
// check for user
$user = $db->getUserByMobileAndCountry($mobile, $country);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["user"]["name"] = $user["name"];
$response["user"]["mobile"] = $user["mobile"];
$response["user"]["country"] = $user["country"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
} else {
echo "Calendar API";
}
JSONPaser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
Log.e("JSON", json);
} 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;
}
}
Stack trace
11-11 06:13:15.086: E/JSON Parser(28899): Error parsing data org.json.JSONException: End of input at character 0 of
11-11 06:13:15.096: D/AndroidRuntime(28899): Shutting down VM
11-11 06:13:15.096: W/dalvikvm(28899): threadid=1: thread exiting with uncaught exception (group=0x418a0da0)
11-11 06:13:15.106: E/AndroidRuntime(28899): FATAL EXCEPTION: main
11-11 06:13:15.106: E/AndroidRuntime(28899): Process: com.calendarapp, PID: 28899
11-11 06:13:15.106: E/AndroidRuntime(28899): java.lang.NullPointerException
11-11 06:13:15.106: E/AndroidRuntime(28899): at com.calendarapp.LoginActivity$ProcessLogin.onPostExecute(LoginActivity.java:172)
11-11 06:13:15.106: E/AndroidRuntime(28899): at com.calendarapp.LoginActivity$ProcessLogin.onPostExecute(LoginActivity.java:1)
11-11 06:13:15.106: E/AndroidRuntime(28899): at android.os.AsyncTask.finish(AsyncTask.java:632)
11-11 06:13:15.106: E/AndroidRuntime(28899): at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-11 06:13:15.106: E/AndroidRuntime(28899): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-11 06:13:15.106: E/AndroidRuntime(28899): at android.os.Handler.dispatchMessage(Handler.java:102)
11-11 06:13:15.106: E/AndroidRuntime(28899): at android.os.Looper.loop(Looper.java:157)
11-11 06:13:15.106: E/AndroidRuntime(28899): at android.app.ActivityThread.main(ActivityThread.java:5356)
11-11 06:13:15.106: E/AndroidRuntime(28899): at java.lang.reflect.Method.invokeNative(Native Method)
11-11 06:13:15.106: E/AndroidRuntime(28899): at java.lang.reflect.Method.invoke(Method.java:515)
11-11 06:13:15.106: E/AndroidRuntime(28899): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
11-11 06:13:15.106: E/AndroidRuntime(28899): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
11-11 06:13:15.106: E/AndroidRuntime(28899): at dalvik.system.NativeStart.main(Native Method)

Android - Error parsing data org.json.jsonexception end of input at character 0

I have been looking over my code all day and can not find why this is happening. data is inputed on database but android application always crash when i'm submit a new data.
Here Register.java
public class Register extends Activity implements OnClickListener{
private EditText nama, alamat, noidentitas, notelepon, username, password;
private Button rgister, bktlogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.43.226/jualan/login/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
nama = (EditText)findViewById(R.id.et_nama);
alamat = (EditText)findViewById(R.id.et_alamat);
noidentitas = (EditText)findViewById(R.id.et_noidentitas);
notelepon = (EditText)findViewById(R.id.et_notelepon);
username = (EditText)findViewById(R.id.et_username);
password = (EditText)findViewById(R.id.et_password);
rgister = (Button)findViewById(R.id.bt_register);
rgister.setOnClickListener(this);
bktlogin = (Button)findViewById(R.id.bktologin);
bktlogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bt_register:
new CreateUser().execute();
break;
case R.id.bktologin:
Intent ii = new Intent(this, Login.class);
startActivity(ii);
break;
default:
break;
}
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String nm = nama.getText().toString();
String almt = alamat.getText().toString();
String noid = noidentitas.getText().toString();
String notelp = notelepon.getText().toString();
String user = username.getText().toString();
String pass = password.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nama", nm));
params.add(new BasicNameValuePair("alamat", almt));
params.add(new BasicNameValuePair("noidentitas", noid));
params.add(new BasicNameValuePair("notelepon", notelp));
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pass));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
//Intent i = new Intent(Register.this, Login.class);
//startActivity(i);
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Here my JSONParser.java
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;
}
}
And here my php code register.php
<?php
include('connection.php');
$id = (int)$_POST['id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$noidentitas = (int)$_POST['noidentitas'];
$notelepon = (int)$_POST['notelepon'];
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'insert into akun (nama, alamat, noidentitas, notelepon, username, password) values ("'.$nama.'", "'.$alamat.'", "'.$noidentitas.'", "'.$notelepon.'", "'.$username.'", "'.$password.'")';
if($id > 0){
$query = 'update akun set nama = "'.$nama.'", alamat = "'.$alamat.'", noidentitas = "'.$noidentitas.'", notelepon = "'.$notelepon.'", username = "'.$username.'", password = "'.$password.'" where id = '.$id;
$result=mysql_query($query);
}
mysql_query($query) or die(mysql_error());
?>
And logcat output is
08-17 20:13:06.215: E/JSON Parser(28309): Error parsing data org.json.JSONException: End of input at character 0 of
08-17 20:13:06.215: W/dalvikvm(28309): threadid=11: thread exiting with uncaught exception (group=0x4118a2a0)
08-17 20:13:06.215: E/AndroidRuntime(28309): FATAL EXCEPTION: AsyncTask #1
08-17 20:13:06.215: E/AndroidRuntime(28309): java.lang.RuntimeException: An error occured while executing doInBackground()
08-17 20:13:06.215: E/AndroidRuntime(28309): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-17 20:13:06.215: E/AndroidRuntime(28309): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.lang.Thread.run(Thread.java:856)
08-17 20:13:06.215: E/AndroidRuntime(28309): Caused by: java.lang.NullPointerException
08-17 20:13:06.215: E/AndroidRuntime(28309): at akun.Register$CreateUser.doInBackground(Register.java:143)
08-17 20:13:06.215: E/AndroidRuntime(28309): at akun.Register$CreateUser.doInBackground(Register.java:1)
08-17 20:13:06.215: E/AndroidRuntime(28309): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-17 20:13:06.215: E/AndroidRuntime(28309): ... 5 more
Change your code in register.php
if($id > 0){
$query = 'update akun set nama = "'.$nama.'", alamat = "'.$alamat.'", noidentitas = "'.$noidentitas.'", notelepon = "'.$notelepon.'", username = "'.$username.'", password = "'.$password.'" where id = '.$id;
} else {
$query = 'insert into akun (nama, alamat, noidentitas, notelepon, username, password) values ("'.$nama.'", "'.$alamat.'", "'.$noidentitas.'", "'.$notelepon.'", "'.$username.'", "'.$password.'")';
}
$result=mysql_query($query);
if ($result) { // This validates if Query was successful
echo '{"success":1,
"message":"Registered Successfully"}';
} else {
echo '{"success":2,
"message":"Registration failed"}';
}
If you are trying to get a json response from a url, then dont use die mysql error. A json response must contain a valid json content.

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