App has stopped working Android Jsonparser - java

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

Related

Fatal Exception: AsyncTask #1 - doInBackground()

I am having a exception that I can't resolved by the debugger log.
I am new to eclipse, so I would like you to help, it would be perfect.
So I got 2 webservices which are being called in a fragment to populate a listview and a spinner in that fragment.
The first webservice is called oncreateview(), and populates the spinner successfully.
The second webservice is called by a button click event, and will get another response (this one with two posts variables).
The Json response is correct, but it gets a exception, in the line(ScheduleList.add(Sche);), but strangely on other class (not this one).
I got two models classes, "Schedule" and "Teacher" to interact with each webservice.
Do you think that is something to do with two async functions on the same fragment?
private class GetTeachersInfo extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("A processar horários..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String professor = arg[0];
String dia_Semana = arg[1];
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("professor", professor));
params.add(new BasicNameValuePair("Dia_Semana", dia_Semana));
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TEACHERSINFO, ServiceHandler.POST, params);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray schedules = jsonObj
.getJSONArray("horarios");
for (int i = 0; i < schedules.length(); i++) {
JSONObject ScheObj = (JSONObject) schedules.get(i);
Schedule Sche = new Schedule(ScheObj.getInt("Cod_Horario"),ScheObj.getString("T_Entrada"),
ScheObj.getString("T_Saida"),ScheObj.getString("Dia_Semana"),ScheObj.getString("Professor"),ScheObj.getString("Disciplina"),ScheObj.getString("Sala"),ScheObj.getString("Turma"));
ScheduleList.add(Sche);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
Edit:
Error log:
06-07 08:53:59.009: E/Response:(1816): > {"horarios":[{"Cod_Horario":5,"T_Entrada":"08:20","T_Saida":"09:05","Dia_Semana":"4\u00aa Feira","Professor":"Ligia Sofia da Costa Nunes","Disciplina":"Ed.Fisic","Sala":"GIN","Turma":"10-F"},{"Cod_Horario":6,"T_Entrada":"09:05","T_Saida":"09:50","Dia_Semana":"4\u00aa Feira","Professor":"Ligia Sofia da Costa Nunes","Disciplina":"Ed.Fisic","Sala":"GIN","Turma":"10-F"},{"Cod_Horario":9,"T_Entrada":"11:45","T_Saida":"12:30","Dia_Semana":"4\u00aa Feira","Professor":"Ligia Sofia da Costa Nunes","Disciplina":"Ed.Fisic","Sala":"GIN","Turma":"11-G"},{"Cod_Horario":10,"T_Entrada":"12:30","T_Saida":"13:15","Dia_Semana":"4\u00aa Feira","Professor":"Ligia Sofia da Costa Nunes","Disciplina":"Ed.Fisic","Sala":"GIN","Turma":"11-G"}],"success":1}
06-07 08:57:05.002: W/dalvikvm(1816): threadid=11: thread exiting with uncaught exception (group=0xb2caab20)
06-07 08:57:10.922: E/AndroidRuntime(1816): FATAL EXCEPTION: AsyncTask #1
06-07 08:57:10.922: E/AndroidRuntime(1816): Process: info.androidhive.tabsswipe, PID: 1816
06-07 08:57:10.922: E/AndroidRuntime(1816): java.lang.RuntimeException: An error occured while executing doInBackground()
06-07 08:57:10.922: E/AndroidRuntime(1816): at android.os.AsyncTask$3.done(AsyncTask.java:300)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
06-07 08:57:10.922: E/AndroidRuntime(1816): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.lang.Thread.run(Thread.java:841)
06-07 08:57:10.922: E/AndroidRuntime(1816): Caused by: java.lang.NullPointerException
06-07 08:57:10.922: E/AndroidRuntime(1816): at info.androidhive.tabsswipe.ProfessoresFragment$GetTeachersInfo.doInBackground(ProfessoresFragment.java:210)
06-07 08:57:10.922: E/AndroidRuntime(1816): at info.androidhive.tabsswipe.ProfessoresFragment$GetTeachersInfo.doInBackground(ProfessoresFragment.java:1)
06-07 08:57:10.922: E/AndroidRuntime(1816): at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-07 08:57:10.922: E/AndroidRuntime(1816): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-07 08:57:10.922: E/AndroidRuntime(1816): ... 4 more
06-07 08:57:11.642: E/WindowManager(1816): android.view.WindowLeaked: Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b3126950 V.E..... R......D 0,0-456,144} that was originally added here
06-07 08:57:11.642: E/WindowManager(1816): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
06-07 08:57:11.642: E/WindowManager(1816): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
06-07 08:57:11.642: E/WindowManager(1816): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
06-07 08:57:11.642: E/WindowManager(1816): at android.app.Dialog.show(Dialog.java:286)
06-07 08:57:11.642: E/WindowManager(1816): at info.androidhive.tabsswipe.ProfessoresFragment$GetTeachersInfo.onPreExecute(ProfessoresFragment.java:181)
06-07 08:57:11.642: E/WindowManager(1816): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
06-07 08:57:11.642: E/WindowManager(1816): at android.os.AsyncTask.execute(AsyncTask.java:535)
06-07 08:57:11.642: E/WindowManager(1816): at info.androidhive.tabsswipe.ProfessoresFragment$1.onClick(ProfessoresFragment.java:74)
06-07 08:57:11.642: E/WindowManager(1816): at android.view.View.performClick(View.java:4438)
06-07 08:57:11.642: E/WindowManager(1816): at android.view.View$PerformClick.run(View.java:18422)
06-07 08:57:11.642: E/WindowManager(1816): at android.os.Handler.handleCallback(Handler.java:733)
06-07 08:57:11.642: E/WindowManager(1816): at android.os.Handler.dispatchMessage(Handler.java:95)
06-07 08:57:11.642: E/WindowManager(1816): at android.os.Looper.loop(Looper.java:136)
06-07 08:57:11.642: E/WindowManager(1816): at android.app.ActivityThread.main(ActivityThread.java:5001)
06-07 08:57:11.642: E/WindowManager(1816): at java.lang.reflect.Method.invokeNative(Native Method)
06-07 08:57:11.642: E/WindowManager(1816): at java.lang.reflect.Method.invoke(Method.java:515)
06-07 08:57:11.642: E/WindowManager(1816): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-07 08:57:11.642: E/WindowManager(1816): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-07 08:57:11.642: E/WindowManager(1816): at dalvik.system.NativeStart.main(Native Method)
Full class code:
public class TurmasFragment extends Fragment {
private ListView listviewHorarios;
private Spinner spinnerTurmas;
private Spinner spinnerDia_Semana;
private Button buttonSearch;
// array list for spinner adapter
private ArrayList<Class> ClassList;
private ArrayList<Schedule> ScheduleList;
ProgressDialog pDialog;
// API urls
// Url to get all teachers
private String URL_CLASSES = "http://10.0.2.2/android/GetAllClassesJson.php";
private String URL_CLASSESINFO = "http://10.0.2.2/android/GetClassJson.php";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_turmas, container, false);
listviewHorarios = (ListView) rootView.findViewById(R.id.list);
spinnerTurmas = (Spinner) rootView.findViewById(R.id.spinner);
spinnerDia_Semana = (Spinner) rootView.findViewById(R.id.spinner2);
buttonSearch = (Button) rootView.findViewById(R.id.button);
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// new category name
String turma = spinnerTurmas.getSelectedItem().toString();
String dia_Semana = spinnerDia_Semana.getSelectedItem().toString();
//String newCategory = txtCategory.getText().toString();
// Call a sync task to create new category
new GetClassesInfo().execute(turma, dia_Semana);
}
});
ClassList = new ArrayList<Class>();
//spinnerProfessores.setOnItemSelectedListener(this);
new GetClasses().execute();
return rootView;
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < ClassList.size(); i++) {
lables.add(ClassList.get(i).getTurma());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerTurmas.setAdapter(spinnerAdapter);
}
private void populateListView() {
ListScheduleAdapter adapter = new ListScheduleAdapter(getActivity(), ScheduleList);
listviewHorarios.setAdapter(adapter);
}
private class GetClasses extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("A processar turmas..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CLASSES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray classes = jsonObj
.getJSONArray("turmas");
for (int i = 0; i < classes.length(); i++) {
JSONObject ClaObj = (JSONObject) classes.get(i);
Class cla = new Class(ClaObj.getInt("Cod_Turma"),
ClaObj.getString("Turma"));
ClassList.add(cla);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetClassesInfo extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("A processar horários..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String turma = arg[0];
String dia_Semana = arg[1];
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Turma", turma));
params.add(new BasicNameValuePair("Dia_Semana", dia_Semana));
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CLASSESINFO, ServiceHandler.POST, params);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray schedules = jsonObj
.getJSONArray("horarios");
for (int i = 0; i < schedules.length(); i++) {
JSONObject ScheObj = (JSONObject) schedules.get(i);
Schedule Sche = new Schedule(ScheObj.getInt("Cod_Horario"),ScheObj.getString("T_Entrada"),
ScheObj.getString("T_Saida"),ScheObj.getString("Dia_Semana"),ScheObj.getString("Professor"),ScheObj.getString("Disciplina"),ScheObj.getString("Sala"),ScheObj.getString("Turma"));
ScheduleList.add(Sche);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateListView();
}
}
}

AsyncTask#1 an error occured while executing doInBackgroud

I got this error whenever I change my URL to my online hosting, but if I change to 10.0.2.2 everything seems fine and running.
LogCat
02-01 23:02:18.302 17643-18052/com.example.jithea.testlogin E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x40d8d9a8)
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: uncaught exception occurred
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ Caused by: java.lang.NullPointerException
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ ... 4 more
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: calling UncaughtExceptionHandler
02-01 23:02:18.315 17643-18052/com.example.jithea.testlogin 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:838)
Caused by: java.lang.NullPointerException
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
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:838)
02-01 23:02:18.371 17643-17659/com.example.jithea.testlogin I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x528dc150) fps:43.08, dur:1044.57, max:73.51, min:6.02
And here's my NewsActivity.java
public class NewsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParserNews jParser = new JSONParserNews();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://agustiniancampusevents.site40.net/newsDB/get_all_news.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_PID = "pid";
private static final String TAG_NEWSTITLE = "newstitle";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
// 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 AdapterView.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(),
ViewNewsActivity.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(NewsActivity.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) {
// 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_NEWS);
// 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 newstitle = c.getString(TAG_NEWSTITLE);
// 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_NEWSTITLE, newstitle);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
ViewNewsActivity.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(
NewsActivity.this, productsList,
R.layout.news_list_item, new String[]{TAG_PID,
TAG_NEWSTITLE},
new int[]{R.id.pid, R.id.newstitle});
// updating listview
setListAdapter(adapter);
}
});
}
}
}

storing JSON to SharedReferences

I'm implementing JSON Parse in Android. The app connect to the url to retrieve JSON and return a String, everything work fine. Now I want to store JSON String to ShareReferences so user still can see the ListView if no internet connection. Here is my code
if (isInternetPresent) { //check internet connection
ServiceHandler sh = new ServiceHandler();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<TVSchedModel>>();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(URL, ServiceHandler.GET); //connect to url and return a string
Editor editor = sharedpreferences.edit();
editor.putString("JSON", jsonStr);
editor.commit();
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(),
"Cannot connect to server", Toast.LENGTH_SHORT)
.show();
}
});
jsonStr = sharedpreferences.getString("JSON", "");
Log.i("JSON Shared", jsonStr);
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray chan = jsonObj.getJSONArray(TAG_CHANNEL);
for (int i = 0; i < chan.length(); i++) {
listDataHeader.add(chan.getJSONObject(i).getString(
"Channel"));
JSONArray sched = jsonObj.getJSONArray(chan
.getJSONObject(i).getString("Channel"));
List<TVSchedModel> result = new ArrayList<TVSchedModel>();
for (int k = 0; k < sched.length(); k++) {
result.add(convertSchedList(sched.getJSONObject(k)));
}
listDataChild.put(listDataHeader.get(i), result);
}
listAdapter.setHeaderList(listDataHeader);
return listDataChild;
} catch (Throwable t) {
t.printStackTrace();
}
If I have internet connection, the app runs fine. Then I turn off the internet, run the app again and get this error even I got the string back that show at Log.i(...)
04-07 23:59:30.066: W/System.err(22797): java.lang.NullPointerException
04-07 23:59:30.066: W/System.err(22797): at com.pnminh.dfytask.TVSchedFragment$AsyncListViewLoader.doInBackground(TVSchedFragment.java:187)
04-07 23:59:30.066: W/System.err(22797): at com.pnminh.dfytask.TVSchedFragment$AsyncListViewLoader.doInBackground(TVSchedFragment.java:1)
04-07 23:59:30.066: W/System.err(22797): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-07 23:59:30.066: W/System.err(22797): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-07 23:59:30.066: W/System.err(22797): at java.lang.Thread.run(Thread.java:841)
What did I do wrong here?
Thanks
The error is coming from this line:
listDataHeader.add(chan.getJSONObject(i).getString("Channel"));
My bet is that listDataHeader is null when no connectivity is detected, and this is because you're just initializing this object in this block:
if (isInternetPresent) {
...
}
Simply initialize it outside (above) this block to let it be reachable even when there's no connectivity.

Android get data from MySql table

I am developing an android app... where I developed a table in MySql and table has certain results for values of 1-10 and all the values are entered seperately ...
in my android application when a particular value is displayed the result of that value has to be taken from the table... but it is not working correctly ...the message is getting like 'unfortunately application closed'... i am adding my code here... please check the code and if found any mistake pls help.....
Activity.java
public class FirstResult extends Activity
{
String pid;
TextView txtName;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://iascpl.com/app/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
//private static final String TAG_PID = "pid";
//private static final String TAG_NUMBER = "number";
//private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.firstresult_xm);
TextView txt1 = (TextView) findViewById (R.id.textView2);
txt1.setText(getIntent().getStringExtra("name10"));
pid = txt1.getText().toString();
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FirstResult.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
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("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "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
txtName = (TextView) findViewById(R.id.textView3);
// display product data in EditText
txtName.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} 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 got all details
pDialog.dismiss();
}
}
}
php file
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM prediction WHERE pid = $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["number"] = $result["number"];
// $product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
my Logcat
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Looper.loop(Looper.java:137)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:44:12.701: E/AndroidRuntime(7643): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:44:12.701: E/AndroidRuntime(7643): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:44:12.701: E/AndroidRuntime(7643): at dalvik.system.NativeStart.main(Native Method)
11-05 11:52:08.052: E/Trace(7805): error opening trace file: No such file or directory (2)
11-05 11:56:14.171: E/AndroidRuntime(7805): FATAL EXCEPTION: main
11-05 11:56:14.171: E/AndroidRuntime(7805): android.os.NetworkOnMainThreadException
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Looper.loop(Looper.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:56:14.171: E/AndroidRuntime(7805): at dalvik.system.NativeStart.main(Native Method)
11-05 11:56:25.961: E/Trace(7893): error opening trace file: No such file or directory (2)
runOnUiThread(new Runnable() {
#Override
public void run()
{
// TODO Auto-generated method stub
try {
txt3.setText(product.getString(TAG_DESCRIPTION));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}else{
// product with pid not found
}
add this line after
/ get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.textView3);
that will solve the issue
You need to post the stack trace of the problem. You will find it in your logcat view. Also, on a sidenote:
runOnUiThread(new Runnable() {
public void run() {
This doesnt make any sense at all at this place because you are basically running a background thread, then you synchronize it and run it on the main thread. Depending on your settings, that won't work because Android does not allow network operations on the main / UI thread.
Edit after LogCat was added:
It's exactly what I mentioned. Android does not allow you to run network traffic on the UI thread. Remove that runOnUiThread stuff from the runOnBackground.
Now to set the data you can two one of two things:
Add the runOnUiThread part where you set the textView. Something like:
runOnUiThread(new Runnable() {
public void run() {
TextView tv = findViewById...
tv.setText(...
}
}
Return the object you need. This is actually how AsyncTask is supposed to work:
In your AsyncTask's runOnBackground, you'd do:
return product.getString(TAG_DESCRIPTION)
Then, in onPostExecute you get that String and set it to your TextViews.

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

Categories