Android Json HttpGet/Post HttpResponse - java

I am trying to take a product from mysql database according to its barcode number. I checked my php codes they are working but on android side i am taking an error.
Here my GetProductDetails class (i think this part is ok);
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Query_product extends Activity {
EditText txtId, txtName, txtPrice, txtDesc;
Button btnSave, btnDelete;
String ID = "";
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url_product_details = "http://10.0.2.2/ssa/get_product_details.php";
private static final String url_update_product = "http://10.0.2.2/ssa/update_product.php";
private static final String url_delete_product = "http://10.0.2.2/ssa/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.query_prod);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
ID += " " + getIntent().getExtras().getString(Constants.ID);
pid = ID;
new GetProductDetails().execute();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
class GetProductDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Query_product.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
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
txtId = (EditText) findViewById(R.id.inputId);
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtId.setText(product.getString(TAG_PID));
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}
else
{
String error = "Not found!";
Toast.makeText(Query_product.this, error, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
Here makeHttpRequest class;
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;
}
}
I couldn't be able to solve the problem. Program runs until this line;
HttpResponse httpResponse = httpClient.execute(httpGet);
Logcat errors;
12-14 18:05:30.994: E/AndroidRuntime(986): FATAL EXCEPTION: main
12-14 18:05:30.994: E/AndroidRuntime(986): android.os.NetworkOnMainThreadException
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.Socket.connect(Socket.java:842)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:66)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.Query_product$GetProductDetails$1.run(Query_product.java:134)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.handleCallback(Handler.java:725)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Looper.loop(Looper.java:137)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-14 18:05:30.994: E/AndroidRuntime(986): at dalvik.system.NativeStart.main(Native Method)
12-14 18:10:31.483: I/Process(986): Sending signal. PID: 986 SIG: 9
12-14 18:10:33.372: D/gralloc_goldfish(1025): Emulator without GPU emulation detected.

You cannot perform network tasks on the main thread because it might block your application in case the network task takes a very long time. You need to run such tasks in the background using AsyncTask instead.
Here's the documentation.

Try using the below code inside your main activity below setContentView(), to avoid the networkOnmainThread exception..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Looks like the error is not of json.
You are trying to call a url from Main Thread which is not allowed from android 4.0
Try using AsynTask or call the url from secondary thread.

Related

App has stopped working Android Jsonparser

I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil 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.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasda‌​sdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}

Android Application Force closing (retrieving data)

I am new to Android application development and Java programming, currently, I'm working on a project to retrieve from my database the status of a service. However, the application will stop working whenever I tried to submit my tracking ID.
MainActivity.java
package com.example.trackstatus;
import com.example.testapp.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnViewStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
// view products click event
btnViewStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching View status activity
Intent i = new Intent(getApplicationContext(), ViewTrackingStatusActivity.class);
startActivity(i);
}
});
}}
TrackStatus Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package = "com.example.trackstatus"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="20" />
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- View Tracking Status Activity -->
<activity
android:name=".ViewTrackingStatusActivity"
android:label="View Tracking Status" >
</activity>
</application>
</manifest>
ViewTrackingStatusActivity.java
package com.example.trackstatus;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.testapp.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ViewTrackingStatusActivity extends Activity{
TextView textView1;
EditText trackingNumberText;
Button btnViewStatus;
String tid;
String tracking;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// url to get service status
private static String url = "http://10.0.2.2/1201716f/android%20connect/get_svc.php?tid=0";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TRACKING = "tracking";
private static final String TAG_TID = "tid";
public String trackingno;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
trackingno = trackingNumberText.getText().toString();
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
Intent intent = getIntent();
tid = intent.getStringExtra(TAG_TID);
// Getting tracking status details in background thread
new GetStatusDetails().execute();
//Toast.makeText(getApplicationContext(),"Hello",
// Toast.LENGTH_LONG).show();
}
class GetStatusDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewTrackingStatusActivity.this);
pDialog.setMessage("Loading details");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tid", trackingno));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
// check your log for json response
Log.d("Tracking Status Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray trackingObj = json.getJSONArray(TAG_TRACKING); // JSON Array
// get first product object from JSON Array
JSONObject tracking = trackingObj.getJSONObject(0);
// display tracking status in ToastBox
Toast.makeText(ViewTrackingStatusActivity.this,json.getString(TAG_TRACKING),Toast.LENGTH_LONG).show();
}
else
{
//service with tid not found
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
return null;
}
}
}
JSONParser.java
package com.example.trackstatus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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;
}
}
Logcat
08-19 23:52:46.644: D/AndroidRuntime(3809): Shutting down VM
08-19 23:52:46.644: W/dalvikvm(3809): threadid=1: thread exiting with uncaught exception (group=0x41b37700)
08-19 23:52:46.654: E/AndroidRuntime(3809): FATAL EXCEPTION: main
08-19 23:52:46.654: E/AndroidRuntime(3809): android.os.NetworkOnMainThreadException
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.Socket.connect(Socket.java:842)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.JSONParser.makeHttpRequest(JSONParser.java:63)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.ViewTrackingStatusActivity$GetStatusDetails$1.run(ViewTrackingStatusActivity.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.handleCallback(Handler.java:730)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Looper.loop(Looper.java:137)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.app.ActivityThread.main(ActivityThread.java:5293)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
08-19 23:52:46.654: E/AndroidRuntime(3809): at dalvik.system.NativeStart.main(Native Method)
08-19 23:52:49.086: I/Process(3809): Sending signal. PID: 3809 SIG: 9
According to your LogCat message:
Caused by: java.lang.NullPointerException at com.example.trackstatus.ViewTrackingStatusActivity.onCreate(ViewTrackingStatusActivity.java:55)
You are missing :
setContentView(R.layout.your_layout);
where your EditText trackingNumberText must be declared.
thats the reason for what trackingNumberText is null
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
More info:
setContentView() method
Update:
Since you have this new exception: NetworkOnMainThreadException
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
you have to implement the use of AsyncTask
And hey! you don´t need to use runOnUiThread inside the doInBackground() method of the Asynctask :P:
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Move the lines that implies operations on UI thread like
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
to the onPostExecute() method of the Asynctask
The error is in Line55
String trackingno = trackingNumberText.getText().toString();
trackingNumberText is NULL
instead try to do NULL check
String trackingno = "";
if(trackingNumberText.getText().length() > 0)
{
trackingno = trackingNumberText.getText().toString();
} else {
Toast.makeText(getApplicationContext(), "Enter values", Toast.LENGTH_LONG).show();
return;
}
EDIT:
You have to send all requests to server in Background Thread, use AsyncTask
Here is the detailed example for performing Network Operation.

FATAL EXCEPTION: AsyncTask, receiving json

Im doing some database work in my app, i want to pull all the locations from my web database and show it in my listview in the app. Ive created the "API" where the respons is Json.
The link where the json is: http://000100023.host56.com/db_all.php
Using this tutorial: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
The Logcat:
11-14 16:50:21.508: E/AndroidRuntime(22809): FATAL EXCEPTION: AsyncTask #1
11-14 16:50:21.508: E/AndroidRuntime(22809): Process: com.spxc.nightclubratings, PID: 22809
11-14 16:50:21.508: E/AndroidRuntime(22809): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.lang.Thread.run(Thread.java:841)
11-14 16:50:21.508: E/AndroidRuntime(22809): Caused by: java.lang.NullPointerException
11-14 16:50:21.508: E/AndroidRuntime(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.doInBackground(SearchLocationActivity.java:132)
11-14 16:50:21.508: E/AndroidRuntime(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.doInBackground(SearchLocationActivity.java:1)
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$2.call(AsyncTask.java:288)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
11-14 16:50:21.508: E/AndroidRuntime(22809): ... 4 more
11-14 16:50:22.199: E/WindowManager(22809): android.view.WindowLeaked: Activity com.spxc.nightclubratings.SearchLocationActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42313208 V.E..... R......D 0,0-729,192} that was originally added here
11-14 16:50:22.199: E/WindowManager(22809): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
11-14 16:50:22.199: E/WindowManager(22809): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
11-14 16:50:22.199: E/WindowManager(22809): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Dialog.show(Dialog.java:286)
11-14 16:50:22.199: E/WindowManager(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.onPreExecute(SearchLocationActivity.java:119)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.AsyncTask.execute(AsyncTask.java:535)
11-14 16:50:22.199: E/WindowManager(22809): at com.spxc.nightclubratings.SearchLocationActivity.onCreate(SearchLocationActivity.java:59)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Activity.performCreate(Activity.java:5243)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.access$700(ActivityThread.java:135)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.Handler.dispatchMessage(Handler.java:102)
**11-14 16:50:22.199: E/WindowManager(22809): at android.os.Looper.loop(Looper.java:137)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-14 16:50:22.199: E/WindowManager(22809): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 16:50:22.199: E/WindowManager(22809): at java.lang.reflect.Method.invoke(Method.java:515)
11-14 16:50:22.199: E/WindowManager(22809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-14 16:50:22.199: E/WindowManager(22809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-14 16:50:22.199: E/WindowManager(22809): at dalvik.system.NativeStart.main(Native Method)
JsonParser:
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;
}
}
SearchLocationAcitivity:
public class SearchLocationActivity 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://http://000100023.host56.com/db_all.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "locations";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_location);
// 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();
pDialog = new ProgressDialog(SearchLocationActivity.this);
pDialog.setMessage("Loading locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// 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);
}
} else {
// 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);
}
} catch (JSONException e) {
e.printStackTrace();
}
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(
SearchLocationActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Any help is much appreciated!
your URL string is wrong, you wrote it like:
Private static String url_all_products = "http://http://000100023.host56.com/db_all.php";
it should be:
Private static String url_all_products = "http://000100023.host56.com/db_all.php";
one http:// is enough ;)
initilize jParser in the onCreate
JSONParser jParser;
in onCreate
jParser = new JSONParser();

Getting an error when connecting from android to PHP server

I have an android application project that connect to PHP server that I write it in codeigniter.
My JSONparser is:
package com.example.com.tourism;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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 method
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 my activity java code that connect to the server is
package com.example.com.tourism;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SignUp extends Activity {
EditText first,last,birth ,pass;
private ProgressDialog pDialog;
private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
Button signUp=(Button)findViewById(R.id.sign_up);
first =(EditText) findViewById(R.id.edfname);
last =(EditText) findViewById(R.id.edlname);
pass =(EditText) findViewById(R.id.edpass);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createnewuser().execute();
}
});
}
class Createnewuser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("Creating User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = first.getText().toString();
String price = last.getText().toString();
String description = pass.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", name));
params.add(new BasicNameValuePair("last_name", price));
params.add(new BasicNameValuePair("password", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
and the error in log cat is
07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground()
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.lang.Thread.run(Thread.java:856)
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98)
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-07 11:30:44.229: E/AndroidRuntime(20514): ... 4 more
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames! The application may be doing too much work on its main thread.
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames! The application may be doing too much work on its main thread.
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.Dialog.show(Dialog.java:281)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.execute(AsyncTask.java:534)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View.performClick(View.java:4204)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View$PerformClick.run(View.java:17355)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.handleCallback(Handler.java:725)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Looper.loop(Looper.java:137)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:30:46.019: E/WindowManager(20514): at dalvik.system.NativeStart.main(Native Method)
i don't know where the problem is, please help me
is my code incorrect ???
if any one have correct code please give it to me i am using codeigniter for php and this is the code that i call it above
function register_get()
{
$json = array('status' => false );
if($this->input->post()==null){
$this -> response($json, 200);
}
$firstname = $this->post("first_name");
$lastname = $this->post("last_name");
$password = $this->post("password");
if(!$firstname || !$lastname || !$password){
$json['status'] = "wrong insert";
$this -> response($json, 200);
}
$this->load->model('Data_model');
$result = $this->Data_model->search($firstname, $lastname);
if($result)
{
$this->Data_model->insert($firstname,$lastname,$password);
$json['status'] = true;
}
// here if false..
$this -> response($json, 200);
}
There are issues with your PHP. You are not passing back any JSON. You will need to change your script to encode your array into JSON.
$result = json_encode($json)
Returning the actual JSON will help. Make sure you are not returning any HTML either. Your Java is trying to parse a JSON response, but you are responding with <!DOCTYPE...

Android: Inserting space in an edittext causes a crash

My edit text serves as a search box, and I am getting movies from rotten tomatoes API, using the text inside my edit text, problem is. when a space is inserted the application crashes, I am assuming that I need to convert the spaces into +'s, but I have no clue how where to add this code or how exactly, I hope someone here will be able to help me.
this is my code:
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public final static int ACTIVITY_WEB_ADD = 3;
public List<String> movieTitles;
public List<String> movieSynopsis;
public List<String> movieImgUrl;
private ProgressDialog pDialog;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65a54w433cab9rbsq";
// the number of movies to show
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
// if the request above completed successfully, this method will
// automatically run so you can do something with the response
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MovieAddFromWeb.this);
pDialog.setMessage("Searching...");
pDialog.show();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
// newly added
movieSynopsis = new ArrayList<String>();
movieImgUrl = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
movieSynopsis.add(movie.getString("synopsis"));
movieImgUrl.add(movie.getJSONObject("posters").getString(
"profile"));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
pDialog.dismiss();
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
// newly added
openMovieEditor.putExtra("movieSynopsis", movieSynopsis.get(position));
openMovieEditor.putExtra("movieImgUrl", movieImgUrl.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
}
this is the log with the error:
01-14 20:19:19.591: D/Test(907): Couldn't make a successful request!
01-14 20:19:19.690: D/AndroidRuntime(907): Shutting down VM
01-14 20:19:19.700: W/dalvikvm(907): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
01-14 20:19:19.801: E/AndroidRuntime(907): FATAL EXCEPTION: main
01-14 20:19:19.801: E/AndroidRuntime(907): java.lang.NullPointerException
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONObject.<init>(JSONObject.java:154)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONObject.<init>(JSONObject.java:171)
01-14 20:19:19.801: E/AndroidRuntime(907): at il.jb.projectpart2.MovieAddFromWeb$RequestTask.onPostExecute(MovieAddFromWeb.java:152)
01-14 20:19:19.801: E/AndroidRuntime(907): at il.jb.projectpart2.MovieAddFromWeb$RequestTask.onPostExecute(MovieAddFromWeb.java:1)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.Looper.loop(Looper.java:137)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-14 20:19:19.801: E/AndroidRuntime(907): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:19:19.801: E/AndroidRuntime(907): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 20:19:19.801: E/AndroidRuntime(907): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-14 20:19:19.801: E/AndroidRuntime(907): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-14 20:19:19.801: E/AndroidRuntime(907): at dalvik.system.NativeStart.main(Native Method)
You should use standard URL encoding as follows:
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ URLEncoder.encode(searchBox.getText(), "UTF-8")
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
This will replace spaces and all other non-URL-friendly characters with allowed characters (as defined by RFC 1738 and the HTML spec)
Need to see your logcat to make sure that's the actual problem, but from your code it looks like it is at least one of your issues.
Ideally you'd do something like
String search = searchBox.getText();
search = search.replace(" ", "+");
and then use that variable to send to your RequestTask
Source: Android Developers
Conversely, you may be better off doing a full encoding on the string returned instead of just replacing spaces... as other characters will cause you issues as well (?, &, etc)
EDIT: See EJK's answer for the URLEncoding version.

Categories