How to connect my server to my app - php

I am using hostinger.web.tr. And I want to upload small data. They are a username, email, and password. When I click the button; my emulator gives me registered toast message. But when I check my PHPMyAdmin panel; there is no something there. How can I connect my server to my app?
My php folder :
<?php
define('HOST','mysql.hostinger.in');
define('USER','******');
define('PASS','******');
define('DB','******');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
if($username == '' || $password == '' || $email == '')
{
echo 'please fill all values';
}
else{
$sql = "SELECT * FROM signup WHERE username='$username' OR email='$email'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo 'username or email already exist';
}else{
$sql = "INSERT INTO signup (username,password,email) VALUES('$username','$password','$email')";
if(mysqli_query($con,$sql)){
echo 'successfully registered';
}
else{
echo 'oops! Please try again!';
}
}
mysqli_close($con);
} ?>
My android activity :
giris_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
registir();
}
private void registir() {
String user_name_string = kullanıcı_edittext.getText().toString().trim().toLowerCase();
String password_string = sifre_edittext.getText().toString().trim().toLowerCase();
String emai = sonra_sil_edittext.getText().toString().trim().toLowerCase();
register_information(user_name_string, emai, password_string);
}
});
}
private void register_information(String user_name_string, String emai, String password_string) {
String urlSuffix = "?username=" + user_name_string + "&password=" + emai + "&email=" + password_string;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(giris_ekrani.this, "Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Registered", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferReader=null;
try {
URL url=new URL(REGISTER_URL+s);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
bufferReader=new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result=bufferReader.readLine();
return result;
}catch (Exception e){
return null;
}
}
}
RegisterUser ur=new RegisterUser();
ur.execute(urlSuffix);
}
My logcat :
04-18 03:20:40.305 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.314 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.321 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.331 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.340 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.345 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.351 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.357 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.368 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.372 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.385 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.709 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.727 1587-2071/? W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#fd8c4a6 attribute=null, token = android.os.BinderProxy#fabdf40
04-18 03:20:40.741 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.767 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:40.900 1587-1607/? I/WindowManager: Destroying surface Surface(name=Please Wait) called by com.android.server.wm.WindowStateAnimator.destroySurface:2014 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:881 com.android.server.wm.WindowState.destroyOrSaveSurface:2073 com.android.server.wm.AppWindowToken.destroySurfaces:363 com.android.server.wm.WindowStateAnimator.finishExit:565 com.android.server.wm.WindowStateAnimator.stepAnimationLocked:491 com.android.server.wm.WindowAnimator.updateWindowsLocked:303 com.android.server.wm.WindowAnimator.animateLocked:704
04-18 03:20:41.234 5465-5486/something.about.berkay.isim D/EGL_emulation: eglMakeCurrent: 0x9eb9dfe0: ver 2 0 (tinfo 0x9eb96920)
04-18 03:20:43.283 1587-1607/? I/WindowManager: Destroying surface Surface(name=Toast) called by com.android.server.wm.WindowStateAnimator.destroySurface:2014 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:881 com.android.server.wm.WindowState.destroyOrSaveSurface:2073 com.android.server.wm.WindowSurfacePlacer.performSurfacePlacementInner:429 com.android.server.wm.WindowSurfacePlacer.performSurfacePlacementLoop:232 com.android.server.wm.WindowSurfacePlacer.performSurfacePlacement:180 com.android.server.wm.WindowManagerService$H.handleMessage:8079 android.os.Handler.dispatchMessage:102
04-18 03:20:43.492 1347-1369/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 2024872 , only wrote 1872000

Related

Not getting json response from online server

So I came over this tutorial right here https://www.youtube.com/watch?v=mdAXqQoADt8 (last part of it) everything is working absolutly fine when I'm refering to my local server.
Now I switched it up to an online server/database to test if it works the same way. Also here everything is working fine except of the json response in the onPostExecute Method. I'm getting no messages from registration or login anymore. I really can't figure out how to solve this problem and I don't understand why it doesn't work the same way when I switch it up to an online server/database.
Hope anyone here can help me with that. I'll post some code below, maybe somebody can figure it out without doing the whole tutorial.
Thankful for any help!
#Override
protected void onPostExecute(String json) {
try {
Log.d("JSON-String",json+"");
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registrierung erfolgt.", message, code);
}
else if (code.equals("reg_false"))
{
showDialog("Registrierung fehlgeschlagen", message, code);
}
else if(code.equals("login_true"))
{
Intent intent = new Intent(activity, Talkscreen.class); //SPÄTER WIEDER RAUSNEHMEN
activity.startActivity(intent);
activity.finish();
}
else if (code.equals("login_false"))
{
showDialog("Login fehlgeschlagen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It seems you're getting wrong JSON string from the server.
2905-2905/com.appmac.ron.testapp W/System.err: org.json.JSONException: Value <h3>DB< of type java.lang.String cannot be converted to JSONObject
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.appmac.ron.testapp.ServerKlassen.BackgroundTask.onPostExecute(BackgroundTask.java:172)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.appmac.ron.testapp.ServerKlassen.BackgroundTask.onPostExecute(BackgroundTask.java:39)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:651)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask.-wrap1(AsyncTask.java)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.Looper.loop(Looper.java:148)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Above error shows that String could not be converted to JSON object.
Check the server code for any bug.

PHP and Android: java.lang.String cannot be converted to JSONArray

I am getting error when I test below code in Android phone:
org.json.JSONException:
Value <!-- of type java.lang.String cannot be converted to JSONArray
My PHP Code as follows: I have used prepare statement
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/public_html/Config.php');
// Connecting to mysql database
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// json response array
$response = array();
if (isset($_POST['treecondition'])) {
// receiving the post params
$treecondition = $_POST['treecondition'];
// get the tree details for google map marker
if($stmt = $mysqli->prepare("SELECT treeid, treelatitude, treelongitude FROM tree WHERE treecondition = ?")){
$stmt->bind_param("s", $treecondition);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($treeid, $treelatitude, $treelongitude);
if ($stmt->num_rows > 0) {
while($tree = $stmt->fetch()) {
$response['treeid'] = $treeid;
$response['treelatitude'] = $treelatitude;
$response['treelongitude'] = $treelongitude;
echo json_encode($response);
}
}
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Tree list view credentials are wrong. Please try again!";
echo json_encode($response);
}
$mysqli->close();
}
My Android volley code as follows: Used Jsonarray
public void onResponse(String response) {
Log.d(TAG, "Location Response: " + response.toString());
hideDialog();
try {
JSONArray jTreeList = new JSONArray(response);
// boolean error = jObj.getBoolean("error");
ArrayList<LatLng> list = new ArrayList<LatLng>();
// Check for error node in json
for (int i = 0; i < jTreeList.length(); i++) {
JSONObject location = jTreeList.getJSONObject(i);
String treeid = location.getString("treeid");
// String treespecies = location.getString("treespecies");
Double treelatitude = location.getDouble("treelatitude");
Double treelongitude = location.getDouble("treelongitude");
LatLng latlng = new LatLng(treelatitude, treelongitude);
list.add(new LatLng(treelatitude, treelongitude));
// Create a heat map tile provider, passing it the latlngs of the police stations.
HeatmapTileProvider provider = new HeatmapTileProvider.Builder().data(list).build();
// Add a tile overlay to the map, using the heat map tile provider.
mMap.addTileOverlay(new TileOverlayOptions().tileProvider(provider));
// Moving CameraPosition to last clicked position
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
// Setting the zoom level in the map on last position is clicked
mMap.animateCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(3));
}
// Launch
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("search", search);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
Please look of my error after the output of program
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow D/ClusterMapFragment﹕ Location Response:
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ org.json.JSONException: Value <!-- of type java.lang.String cannot be converted to JSONArray
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:96)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:108)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.example.bharat.plantnow.Maps.ClusterMapFragment$2.onResponse(ClusterMapFragment.java:143)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.example.bharat.plantnow.Maps.ClusterMapFragment$2.onResponse(ClusterMapFragment.java:131)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5292)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
11-20 14:32:38.451 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The Json response you receive is not formatted as JSON it contains invalid character '<!--' thats why your jsonparser throw an Jsonexception.
Try to save your php file in cp1252 Encoding
Open your php file in Eclipse
Edit> Set Encoding then set to cp1252
save

PHP web service doesn't work in Android app

I have opened up 4 months old android project and I faced some problems which I didn't have before.
I have a web-service http://tojesttest.byethost22.com/PizzaService/getAndroidOrders.php
which gets me JSONArray when I open it in a browser, but when I call it from inside of android app it gets me in return:
10-16 21:29:35.021 18477-18565/com.example.tomek.pizzaservice E/HTTP: Success!<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("cd6163c2d295cc64f22c62356ba045f4");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://tojesttest.byethost22.com/PizzaService/getAndroidOrders.php?ckattempt=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
I've tried to enable java script in android Internet browser but it was already turned ON.
Piece of code that I'm using:
private static JSONArray loadFromDatabase(String phpFileAddress){
JSONArray jsonArray = null;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(phpFileAddress).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("HTTP", "onFailure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.e("HTTP","Success!" + jsonData);
} else {
Log.e("HTTP","Zła odpowiedź serwera.");
}
}
catch (IOException e) {
Log.e("HTTP","Zła odpowiedź serwera.");
}
}
});
return jsonArray;
}

Display ImageView with JSON, returns no value

My problem is the next ...
Im trying to display a image, that is defined in my phpmyadmin, and hosted in the correspondient folder, but the bitmapfactory returns nothin.
MY JAVA:
if (success == 1) {
// successfully received product details
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
//imageview
imageView1 = (ImageView)findViewById(R.id.imageView1);
imagen_url=product.getString("TAG_IMAGEN");
String imagen_url2=product.optString("TAG_IMAGEN");
byte[] encodeByte = Base64.decode(imagen_url, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
imageView1.setImageBitmap(bitmap);
AND THE PHP
$product["imagen"] = base64_encode($result["imagen"]);
It returns a error:
04-10 04:12:32.344: W/System.err(1424): org.json.JSONException: No value for TAG_IMAGEN
04-10 04:12:32.364: W/System.err(1424): at org.json.JSONObject.get(JSONObject.java:355)
04-10 04:12:32.364: W/System.err(1424): at org.json.JSONObject.getString(JSONObject.java:515)
04-10 04:12:32.374: W/System.err(1424): at com.example.androidhive.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:180)
04-10 04:12:32.374: W/System.err(1424): at android.os.Handler.handleCallback(Handler.java:733)
04-10 04:12:32.374: W/System.err(1424): at android.os.Handler.dispatchMessage(Handler.java:95)
04-10 04:12:32.404: W/System.err(1424): at android.os.Looper.loop(Looper.java:136)
04-10 04:12:32.404: W/System.err(1424): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 04:12:32.404: W/System.err(1424): at java.lang.reflect.Method.invokeNative(Native Method)
04-10 04:12:32.414: W/System.err(1424): at java.lang.reflect.Method.invoke(Method.java:515)
04-10 04:12:32.414: W/System.err(1424): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 04:12:32.414: W/System.err(1424): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 04:12:32.434: W/System.err(1424): at dalvik.system.NativeStart.main(Native Method)
The problem was the TAG, if I put :
imagen_url=product.getString("imagen");
works, but with not :
imagen_url=product.getString("TAG_IMAGEN");
I dont know why, but with this change, it works fine!

app crashes on JSON jparser make http request

hi i use this tutorial for connecting to the mySQL db on the web or local.
here
although the all server side php files are correct and works on the browser, but in Android side the app crashes on this line:
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
with this message: unfortunately app has stopped!
i find out on tutorial page comments that i should change some setting on apache server.
here is my code:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://127.0.0.1/android/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
StrictMode.enableDefaults();
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("LOG", "load data preexecute");
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
Log.i("LOG", "load data inback ");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
Log.i("LOG", "load data inback json 1 ");
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.i("LOG", "load data inback json 2 "+json.toString());
// Check your log cat for JSON reponse
try {
Log.i("LOG", "load data inback json json 3");
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
Log.i("LOG", "load data inback json json 4");
}
} else {
Log.i("LOG", "load data inback json json 5");
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
Log.i("All Products: ","success:"+ success+"");
} catch (JSONException e) {
e.printStackTrace();
Log.i("LOG", "load data inback json on catch");
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
this is log cat:
01-11 13:49:19.163: E/Trace(2045): error opening trace file: No such file or directory (2)
01-11 13:49:19.642: D/gralloc_goldfish(2045): Emulator without GPU emulation detected.
01-11 13:49:26.103: I/LOG(2045): load data preexecute
01-11 13:49:26.583: D/dalvikvm(2045): GC_FOR_ALLOC freed 78K, 3% free 8222K/8391K, paused 155ms, total 170ms
01-11 13:49:26.793: I/LOG(2045): load data inback
01-11 13:49:26.793: I/LOG(2045): load data inback json 1
01-11 13:49:27.022: I/Choreographer(2045): Skipped 38 frames! The application may be doing too much work on its main thread.
01-11 13:49:27.923: W/System.err(2045): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-11 13:49:27.933: W/System.err(2045): at com.mjs.test.phptest92.core.JSONParser.makeHttpRequest(JSONParser.java:61)
01-11 13:49:27.943: W/System.err(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:138)
01-11 13:49:27.943: W/System.err(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
01-11 13:49:27.943: W/System.err(2045): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-11 13:49:27.943: W/System.err(2045): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-11 13:49:27.943: W/System.err(2045): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-11 13:49:27.943: W/System.err(2045): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-11 13:49:27.953: W/System.err(2045): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-11 13:49:27.953: W/System.err(2045): at java.lang.Thread.run(Thread.java:856)
01-11 13:49:27.953: W/System.err(2045): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
01-11 13:49:28.023: W/System.err(2045): at libcore.io.IoBridge.connect(IoBridge.java:114)
01-11 13:49:28.023: W/System.err(2045): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-11 13:49:28.033: W/System.err(2045): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-11 13:49:28.033: W/System.err(2045): at java.net.Socket.connect(Socket.java:842)
01-11 13:49:28.033: W/System.err(2045): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-11 13:49:28.033: W/System.err(2045): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-11 13:49:28.033: W/System.err(2045): ... 15 more
01-11 13:49:28.033: W/System.err(2045): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
01-11 13:49:28.043: W/System.err(2045): at libcore.io.Posix.connect(Native Method)
01-11 13:49:28.053: W/System.err(2045): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
01-11 13:49:28.053: W/System.err(2045): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-11 13:49:28.053: W/System.err(2045): at libcore.io.IoBridge.connect(IoBridge.java:112)
01-11 13:49:28.053: W/System.err(2045): ... 20 more
01-11 13:49:28.053: E/Buffer Error(2045): Error converting result java.lang.NullPointerException
01-11 13:49:28.093: E/JSON Parser(2045): Error parsing data org.json.JSONException: End of input at character 0 of
01-11 13:49:28.123: W/dalvikvm(2045): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
01-11 13:49:28.143: E/AndroidRuntime(2045): FATAL EXCEPTION: AsyncTask #1
01-11 13:49:28.143: E/AndroidRuntime(2045): java.lang.RuntimeException: An error occured while executing doInBackground()
01-11 13:49:28.143: E/AndroidRuntime(2045): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.lang.Thread.run(Thread.java:856)
01-11 13:49:28.143: E/AndroidRuntime(2045): Caused by: java.lang.NullPointerException
01-11 13:49:28.143: E/AndroidRuntime(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:141)
01-11 13:49:28.143: E/AndroidRuntime(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
01-11 13:49:28.143: E/AndroidRuntime(2045): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-11 13:49:28.143: E/AndroidRuntime(2045): ... 4 more
01-11 13:49:28.843: I/Choreographer(2045): Skipped 76 frames! The application may be doing too much work on its main thread.
01-11 13:49:29.163: I/Choreographer(2045): Skipped 89 frames! The application may be doing too much work on its main thread.
01-11 13:49:29.713: E/WindowManager(2045): Activity com.mjs.test.phptest92.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41223f00 that was originally added here
01-11 13:49:29.713: E/WindowManager(2045): android.view.WindowLeaked: Activity com.mjs.test.phptest92.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41223f00 that was originally added here
01-11 13:49:29.713: E/WindowManager(2045): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.Window$LocalWindowManager.addView(Window.java:547)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.Dialog.show(Dialog.java:277)
01-11 13:49:29.713: E/WindowManager(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:124)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.AsyncTask.execute(AsyncTask.java:534)
01-11 13:49:29.713: E/WindowManager(2045): at com.mjs.test.phptest92.AllProductsActivity.onCreate(AllProductsActivity.java:62)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.Activity.performCreate(Activity.java:5008)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.Handler.dispatchMessage(Handler.java:99)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.Looper.loop(Looper.java:137)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-11 13:49:29.713: E/WindowManager(2045): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:49:29.713: E/WindowManager(2045): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:49:29.713: E/WindowManager(2045): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-11 13:49:29.713: E/WindowManager(2045): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-11 13:49:29.713: E/WindowManager(2045): at dalvik.system.NativeStart.main(Native Method)
01-11 13:49:29.713: I/Choreographer(2045): Skipped 32 frames! The application may be doing too much work on its main thread.
how i can solve this problem?
If you are referring to a localhost from your device than use the http://10.0.2.2:8080/ instead of the http://127.0.0.1/ or http://localhost/.
Because your Android emulator is running on a Virtual Machine(QEMU) and you can not connect to a server directly running on your PC.
And If you running your app from Physical android device then please use your network ip from your PC.
for example http://198.10.12.21:80/....

Categories