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();
}
}
}
Related
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":"dasdasdasdasd"},{"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();
}
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);
}
});
}
}
}
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();
Hey guys can you look at my errors, my logcat says it is because i am getting null pointer exception. i don't understand why. I just added a String variable which is "Email" and make the value of my eadd which stands for email address equals to it, then i have these errors now. can you point to me the problem guys?
These are my codes:
**
public class LoginSub extends Activity {
public static String Email;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputEmail;
EditText inputPassword;
TextView TextView1;
// url to create new product
//private static String url_create_product = "http://student-thesis.netii.net/log_in.php";
private static String url_create_product = "http://10.0.2.2/TheCalling/log_in.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Edit Text
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputPassword = (EditText) findViewById(R.id.inputPassword);
// Create button
Button btnLogin = (Button) findViewById(R.id.btnLogin);
// button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new phpconnect().execute();
}
});
Button btnReg = (Button) findViewById(R.id.btnReg);
// button click event
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Register.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class phpconnect extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginSub.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String eadd = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eadd", eadd));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Email.equals(eadd);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
} 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 here's my logcat errors:
**
03-06 22:21:16.428: E/AndroidRuntime(1417): FATAL EXCEPTION: AsyncTask #1
03-06 22:21:16.428: E/AndroidRuntime(1417): java.lang.RuntimeException: An error occured while executing doInBackground()
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.lang.Thread.run(Thread.java:856)
03-06 22:21:16.428: E/AndroidRuntime(1417): Caused by: java.lang.NullPointerException
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:129)
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:1)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
**
Thank you guys.
Remove this block from doInBackGround()
if (success == 1) {
// successfully created product
Intent i = new Intent(LoginSub.this, Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
And add it in onPostExecute() section
protected void onPostExecute(String file_url)
{
// dismiss the dialog once done
pDialog.dismiss();
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
}
else
{
}
}
Some times getApplicationContext() wont provide the exact context values. So pass the
Context context; //declare
context=this;// assigning next line after setcontextview.
then pass the context instead of getApplicationContext() . and check it and also if you want to do any UI updates you are not supposed to do in doinBackground(). You have to do in post execute.
Hope this will help you.
I think because this line
new phpconnect().execute();
and
class phpconnect extends AsyncTask<String, String, String> {
You declare AsyncTask with <String, String, String> but you didn't pass any parameter in .exeute();
Moreover that, from your code you don't want any parameter for AsyncTask so you should declare your Asynctask like this
class phpconnect extends AsyncTask<Void, Void, Void> {
I'm trying to develop an autocomplete location for goofle map. But, I have encountered some errors while developing. I do not know what is the cause of the error.
Below is my code.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ArrayAdapter<String> adapter;
AutoCompleteTextView textView;
Object[] arg0 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, R.layout.item_list);
textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (count % 3 == 1) {
adapter.clear();
// GetPlaces task = new GetPlaces();
// now pass the argument in the textview to the task
new GetPlaces().execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args) {
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ URLEncoder.encode(arg0[0].toString(), "UTF-8")
+ "&types=geocode&language=en&sensor=true&key=<API-key here>");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
// take Google's legible JSON and turn it into one big
// string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
// turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
// now get the JSON array that's inside that object
JSONArray ja = new JSONArray(
predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
// add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
// then our post
#Override
protected void onPostExecute(ArrayList<String> result) {
Log.d("YourApp", "onPostExecute : " + result.size());
// update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.item_list);
adapter.setNotifyOnChange(true);
// attach the adapter to textview
textView.setAdapter(adapter);
for (String string : result) {
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp",
"onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
Here is the logcat error:
10-24 15:10:54.609: E/AndroidRuntime(14346): FATAL EXCEPTION: AsyncTask #1
10-24 15:10:54.609: E/AndroidRuntime(14346): java.lang.RuntimeException: An error occured while executing doInBackground()
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$3.done(AsyncTask.java:278)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.lang.Thread.run(Thread.java:856)
10-24 15:10:54.609: E/AndroidRuntime(14346): Caused by: java.lang.NullPointerException
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:76)
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:1)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$2.call(AsyncTask.java:264)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
The source of the error is obviously in MainActivity line 76, where you are accessing a null object
in 76th line..
use "URLEncoder.encode(args[0].toString()" instead of "URLEncoder.encode(arg0[0].toString()"