I'm developing an Android app which, basing on the GPS location, queries a database to retrieve the nearest places within a certain distance (setting a marker on them).
I followed this tutorial http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/, so I'm trying to do a HttpRequest to retrieve a JSON from the PHP script.
I'm getting a NullPointerException when calling the getJSONArray method.
Here's the logcat
05-27 22:22:56.964: E/AndroidRuntime(26452): FATAL EXCEPTION: main
05-27 22:22:56.964: E/AndroidRuntime(26452): java.lang.NullPointerException
05-27 22:22:56.964: E/AndroidRuntime(26452): at com.example.mypackage.fragments.MyFragment$GetBuildings$1.run(MyFragment.java:130)
05-27 22:22:56.964: E/AndroidRuntime(26452): at android.os.Handler.handleCallback(Handler.java:615)
05-27 22:22:56.964: E/AndroidRuntime(26452): at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 22:22:56.964: E/AndroidRuntime(26452): at android.os.Looper.loop(Looper.java:137)
05-27 22:22:56.964: E/AndroidRuntime(26452): at android.app.ActivityThread.main(ActivityThread.java:4867)
05-27 22:22:56.964: E/AndroidRuntime(26452): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 22:22:56.964: E/AndroidRuntime(26452): at java.lang.reflect.Method.invoke(Method.java:511)
05-27 22:22:56.964: E/AndroidRuntime(26452): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
05-27 22:22:56.964: E/AndroidRuntime(26452): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
05-27 22:22:56.964: E/AndroidRuntime(26452): at dalvik.system.NativeStart.main(Native Method)
Here's the fragment (note that if I put out the AsyncTask the map displays correctly):
public class MyFragment extends Fragment {
MapView mapView;
GoogleMap map;
private ProgressDialog pDialog;
private static String url = "http://mySite/query.php";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
mapView = (MapView) v.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setMyLocationEnabled(true);
MapsInitializer.initialize(this.getActivity());
LocationManager locationManager = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
if (location != null)
{
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(14)
.bearing(0)
.tilt(0)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
new GetBuildings().execute();
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
class GetBuildings extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
getActivity().runOnUiThread(new Runnable()
{
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
public void run() {
JSONParser jparser = new JSONParser();
double lat = location.getLatitude();
double lon = location.getLongitude();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("lat", Double.toString(lat)));
params.add(new BasicNameValuePair("lon", Double.toString(lon)));
JSONObject json = jparser.makeHttpRequest(
url, "POST", params);
try {
JSONArray jarray = json.getJSONArray("Buildings details");// NULLPOINTEREXCEPTION HERE
for(int i = 0; i < jarray.length(); i++)
{
JSONObject object = jarray.getJSONObject(i);
LatLng latlng = new LatLng(Double.parseDouble(object.getString("lat")),
Double.parseDouble(object.getString("lon")));
MarkerOptions mo = new MarkerOptions().position(latlng)
.title(object.getString("name"));
map.addMarker(mo);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if(method == "POST"){
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"){
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) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}
query.php
<?php
$response = array();
$pi = 3.1415926535898;
$earth_radius = 6372.795477598;
$range= 40.0; //km
$mysqli = new mysqli("host", "user", "psw", "db");
$query = "SELECT id, name, city, lat, lon,
($earth_radius*ACOS(
(SIN($pi * $lat / 180)*SIN($pi * lat / 180)) +
(COS($pi * $lat / 180)*COS($pi * lat / 180) * COS(ABS(($pi * $lon / 180) - ($pi * lon / 180))) )
)
) as distance from BuildingsDetails HAVING distance<$range ORDER BY distance";
if ( (isset($_POST['lat'])) && (isset($_POST['lon'])) ) {
$lat = $_POST["lat"];
$lon = $_POST["lon"];
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
$response["Buildings Details"] = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$buildingsdetails = array();
$buildingsdetails["id"] = $row["id"];
$buildingsdetails["name"] = $row["name"];
$buildingsdetails["city"] = $row["city"];
$buildingsdetails["lat"] = $row["lat"];
$buildingsdetails["lon"] = $row["lon"];
$buildingsdetails["distance"] = $row["distance"];
array_push($response["Buildings Details"], $buildingsdetails);
}
echo json_encode($response);
} else {
$response["message"] = "No buildings found";
echo json_encode($response);
}
} else {
$response["message"] = "Missing parameter(s)";
echo json_encode($response);
}
?>
Note that if I set lat and lon values manually in the script and i type the URL in the browser I correctly get the JSON, like this:
{"Buildings Details":[{"id":"3","name":"building1","city":"city1","lat":"52.5014076","lon":"13.4023285","distance":"26.2818230530031"},{"id":"5","name":"building2","city":"city2","lat":"52.379173","lon":"12.819091","distance":"26.4070424101156"},{"id":"26","name":"building3","city":"city3","lat":"52.656543","lon":"13.976542","distance":"32.5675097399059"}]}
So I guess the problem is presenting when the app passes the latitude and longitude parameters to the PHP script. Anyone has ideas?
UPDATE: I really don't know what has changed, but now I don't get any errors. Unfortunately, no markers show up on the map. Null JSON?
You have a problem here :
getActivity().runOnUiThread(new Runnable() {..}
In android you are not allowed to perform network operation on main thread.
Your code most likely doesn't hit the PHP script therefore will result in null.
Related
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();"
I developed an app in which i am receiving latitude and longitude through API REST from my server, so what i want is that the api call will be solved before the display of such coordinates on map. Please guide me how to do this.
I've already implemented a solution but it seems to not work.
From the stack trace I've got this message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pro.rane.myapplication, PID: 1590
java.lang.NullPointerException: Attempt to get length of null array
at pro.rane.myapplication.MapsActivity.onMapReady(MapsActivity.java:160)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:392)
at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82)
at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I am conscious that this error is caused by the fact that function getCoordinates() doesn't work properly. I've also tried in past to use Volley library but it didn't work in same way. How can I make my API request works ?
Please note that the url is working, if you do your own get request on my server you can see the correct result in your browser.
Here's my code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String LATITUDE = "latitude";
private static final String LONGITUDE = "longitude";
private GoogleMap mMap;
private String info;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Bundle b = getIntent().getExtras();
if (b != null)
info = b.getString("qrCodeInformation");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/*connection to obtain the array of positions*/
private static String[][] getCoordinates(String tran_id) throws JSONException {
String dummy_tran_id = "1";
String richiesta = "http://myurl/getArticleTravel?tran_id=" + dummy_tran_id;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpGet request = new HttpGet(richiesta);
request.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = "";
try {
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("Errore http request",""+e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
Log.i(squish.getMessage(), squish.getMessage());
}
}
JSONArray jObject;
String[][] coordinates;
jObject = new JSONArray(result);
String[] latitude = new String[jObject.length()];
String[] longitude = new String[jObject.length()];
for (int i = 0; i < jObject.length(); i++) {
latitude[i] = jObject.getJSONObject(i).getString(LATITUDE);
longitude[i] = jObject.getJSONObject(i).getString(LONGITUDE);
}
coordinates = new String[latitude.length][longitude.length];
for(int i =0; i < latitude.length;i++){
coordinates[i][0] = latitude[i];
coordinates[i][1] = longitude[i];
}
//String[][] dummy_coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"}};
return coordinates;
//return dummy_coordinates;
}
#Override
public void onMapReady(GoogleMap googleMap) {
String[][] coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"},{"40.9027835", "15.496365500000024"}}; //= null;
try {
coordinates = getCoordinates(info);
} catch (JSONException e) {
e.printStackTrace();
}
Integer a;
mMap = googleMap;
View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
for (a = 0; a < coordinates.length; a++) {
if(a==0){
numTxt.setText("Go");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])))
.title("GO")
.snippet("Start point "+ a.toString())
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker)))
);
}else {
numTxt.setText(a.toString());
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])))
.title(a.toString())
.snippet("Arrival point " + a.toString())
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker)))
);
}
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])),5));
}
}
// Convert a view to bitmap
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.disconnect();
}
}
Extend the AsyncTask class and use doInBackground to handle the work from getCoordinates in a background thread.
public class YourAsyncTask extends AsyncTask<Void, Void, YourReturnType> {
public interface OnFinishListener{
void onFinish(YourReturnType result);
}
private OnFinishListener mListener;
public OnFinishListener setOnFinishListener(#Nullable OnFinishListener l){
mListener = l;
}
#Override
protected YourReturnType doInBackground(Void... params) {
// Replace all "YourReturnType" with the actual type/object you want to return
YourReturnType returnValue;
// Do your work here and build/create your returnValue
return returnValue;
}
// This will get called automatically after doInBackground finishes
#Override
protected void onPostExecute(YourReturnType result) {
// If listener is set
if(mListener != null){
mListener.onFinish(result); // Return the returnValue
}
}
}
In your Activity when you want to get the coordinate values, execute your AsyncTask and set the listener interface;
YourAsyncTask yourTask = new YourAsyncTask();
yourTask.execute();
yourTask.setOnFinishListener(new YourAsyncTask.OnFinishListener(){
#Override
public void onFinish(YourReturnType result){
// Retrieve your returned value from result
// And if mMap is ready, perform map actions
}
});
AsyncTask documentation
I am calling an Activity called MapsActivity from a Fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_one, container, false);
ibTrackEmp = (ImageView)rootView.findViewById(R.id.ibTrackEmp);
ibTrackEmp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MapsActivity.class);
startActivity(intent);
}
});
return rootView;
}
Now, in the MapsActivity.java, i call a Web Service as a BackGround Task
private class GetALLGPSTask extends AsyncTask<String, Void, String> {
private TextView textView;
public GetALLGPSTask() {
}
#Override
protected String doInBackground(String... strings) {
String result = "Unable to fetch from SAP";
try {
URL url = new URL(strings[0]);
final String basicAuth = "Basic " + Base64.encodeToString("xxxx:xxxx#1223".getBytes(), Base64.NO_WRAP);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(90000);
urlConnection.setConnectTimeout(55000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty ("Authorization", basicAuth);
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
int responsecode = urlConnection.getResponseCode();
Log.d("ResponseCode", String.valueOf(responsecode));
if(responsecode == 200){
result = "GPS Coordinates Updated Successfully";
try {
JSONArray jsonArray = new JSONArray(builder.toString());
List<Pair<String, String>> allNames = new ArrayList<>();
final int numberOfItemsInResp = jsonArray.length();
for (int i = 0; i < numberOfItemsInResp; i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
String name = jobj.getString("NAME");
String addlatitude = jobj.getString("LATITUDE");
String addlongitude = jobj.getString("LONGITUDE");
LatLng newemp = new LatLng(Double.valueOf(addlatitude), Double.valueOf(addlongitude));
mMap.addMarker(new MarkerOptions().position(newemp).title("UserName: "+name));
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String temp) {
Toast.makeText(MapsActivity.this,
temp, Toast.LENGTH_SHORT).show();
}
Here, the Web Service is getting called, but the app initializes to the first screen.
I get the following error log
--------- beginning of crash
09-27 15:52:31.912 31508-31767/com.example.sd0003.appslider E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.sd0003.appslider, PID: 31508
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalStateException: Not on the main thread
at maps.w.d.a(Unknown Source)
at maps.y.F.a(Unknown Source)
at maps.ad.t.a(Unknown Source)
at ua.onTransact(:com.google.android.gms.DynamiteModulesB:167)
at android.os.Binder.transact(Binder.java:392)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addMarker(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
at com.example.sd0003.appslider.MapsActivity$GetALLGPSTask.doInBackground(MapsActivity.java:152)
at com.example.sd0003.appslider.MapsActivity$GetALLGPSTask.doInBackground(MapsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
09-27 15:52:31.912 31508-31767/com.example.sd0003.appslider E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
09-27 15:52:31.913 31508-31767/com.example.sd0003.appslider D/AppTracker: App Event: crash
09-27 15:52:31.916 31508-31767/com.example.sd0003.appslider E/AbstractTracker: mTrackerAsyncQueryHandler is null
09-27 15:52:31.942 31508-31767/com.example.sd0003.appslider I/Process: Sending signal. PID: 31508 SIG: 9
You should not be performing UI updates from a background thread. In this particular case, you should not be adding markers to your mMap reference.
Instead, you should return a list of location names and latitude/longitude pairs and handle updating the UI from the main thread in onPostExecute. Think about returning a dataset that resembles something like List<Pair<String, LatLng>> locations.
Your implementation would then look like this:
private class GetALLGPSTask extends AsyncTask<String, Void, List<Pair<String, LatLng>>> {
private TextView textView;
public GetALLGPSTask() {
}
#Override
protected List<Pair<String, LatLng>> doInBackground(String... strings) {
List<Pair<String, LatLng>> allLocations = new ArrayList<>();
try {
URL url = new URL(strings[0]);
final String basicAuth = "Basic " + Base64.encodeToString("xxxx:xxxx#1223".getBytes(), Base64.NO_WRAP);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(90000);
urlConnection.setConnectTimeout(55000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty ("Authorization", basicAuth);
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
int responsecode = urlConnection.getResponseCode();
Log.d("ResponseCode", String.valueOf(responsecode));
if(responsecode == 200){
try {
JSONArray jsonArray = new JSONArray(builder.toString());
final int numberOfItemsInResp = jsonArray.length();
for (int i = 0; i < numberOfItemsInResp; i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
String name = jobj.getString("NAME");
String latitude = jobj.getString("LATITUDE");
String longitude = jobj.getString("LONGITUDE");
LatLng latLng = new LatLng(Double.valueOf(addlatitude), Double.valueOf(addlongitude));
allLocations.add(new Pair<>(name, latLng))
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return allLocations;
}
#Override
protected void onPostExecute(List<Pair<String, LatLng>> locations) {
for (Pair<String, LatLng> location : locations) {
mMap.addMarker(new MarkerOptions().position(location.second).title("UserName: " + location.first));
}
}
}
Side note: Your allNames list was never used.
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.
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?