How to list all events on list view with database? - java

The program/apk need to list all titles , but when i run it apk close please help me i dont know what happens really
package com.eu.agendamarinhagrande;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> empresaList;
// url to get all products list
private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";
// JSON Node names
private static final String TAG_TITULO = "Titulo";
// products JSONArray
String resultado = null;
ListView lista;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap para el ListView
empresaList = new ArrayList<HashMap<String, String>>();
LoadAllProducts loadAllProducts = new LoadAllProducts();
// Cargar los productos en el Background Thread
lista = (ListView) findViewById(R.id.agenda);
loadAllProducts.execute(String.valueOf(lista));
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}//fin onCreate
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Antes de empezar el background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("A carregar eventos. Por favor espere...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* obteniendo todos los productos
*/
protected String doInBackground(String... args) {
// Building Parameters
List params = new ArrayList();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params);
StringBuilder sb = new StringBuilder();
// Check your log cat for JSON reponse
Log.d("All Products: ", url_all_empresas.toString());
resultado = sb.toString();
try {
// Checking for SUCCESS TAG
// products found
// Getting Array of Products
JSONArray arrayJson = new JSONArray(resultado);
for (int i = 0; i<arrayJson.length();i++){
// Storing each json item in variable
JSONObject c = arrayJson.getJSONObject(i);
String Titulo = c.getString(TAG_TITULO);
// creating new HashMap
HashMap map = new HashMap();
// adding each child node to HashMap key => value
map.put(TAG_TITULO, Titulo);
empresaList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
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(
MainActivity.this,
empresaList,
R.layout.single_post,
new String[]{
TAG_TITULO
},
new int[]{
R.id.single_post_tv_id
});
// updating listview
//setListAdapter(adapter);
lista.setAdapter(adapter);
}
});
}
}
}

Check this line in your onCreate() method:
loadAllProducts.execute(String.valueOf(lista));
you can not get the string value of a ListView! If you want to get the value of a textView IN the listView, you could add an OnItemClick event to your listView and get the value of the textView in the selected list item like this:
//a variable, you could use from all the methods, that will have as a value the value of the selected TextView
private String selectedValue;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
View view = (View)v.getParent();
TextView textYouNeed = (TextView) view.findViewById(R.id.textViewId);
selectedValue = textYouNeed.getText();
}
and then use this variable in the line I told about above:
loadAllProducts.execute(selectedValue);

06-19 11:07:34.233 13804-13804/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-19 11:07:34.380 13804-13818/com.eu.agendamarinhagrande I/art﹕ Background sticky concurrent mark sweep GC freed 1879(132KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 538KB/605KB, paused 49.704ms total 65.759ms
06-19 11:07:34.380 13804-13804/com.eu.agendamarinhagrande D/AndroidRuntime﹕ Shutting down VM
06-19 11:07:34.380 13804-13804/com.eu.agendamarinhagrande E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.eu.agendamarinhagrande, PID: 13804
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eu.agendamarinhagrande/com.eu.agendamarinhagrande.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.eu.agendamarinhagrande.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Related

Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList in android studio

I am trying to permanently save some of the visited places by the user. So, when ever i run my project in android studio i get the error
"Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList"
Here is my code:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> places= new ArrayList<>();
static ArrayList<LatLng> locations = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.lucifer.memorableplaces", Context.MODE_PRIVATE);
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
places.clear();
latitudes.clear();
longitudes.clear();
locations.clear();
try {
places = (ArrayList<String>)ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList<String>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes", ObjectSerializer.serialize(new ArrayList<String>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
if (places.size() > 0 && latitudes.size() > 0 && longitudes.size() > 0) {
if (places.size() == latitudes.size() && latitudes.size() == longitudes.size()) {
for (int i = 0; i < latitudes.size(); i++) {
locations.add(new LatLng(Double.parseDouble(latitudes.get(i)), Double.parseDouble(longitudes.get(i))));
}
}
} else {
places.add("Add a new place...");
locations.add(new LatLng(0, 0));
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, places);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra("placeNumber", i);
startActivity(intent);
}
});
}
}
and i get the following error:
Process: com.example.lucifer.memorableplaces, PID: 15910
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lucifer.memorableplaces/com.example.lucifer.memorableplaces.MainActivity}: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList
at com.example.lucifer.memorableplaces.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:5301)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2291)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378) 
at android.app.ActivityThread.access$800(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5433) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
at dalvik.system.NativeStart.main(Native Method) 
The error is at
places = (ArrayList)ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList())));
I finally got the answer, the error was caused because i was casting a class to arrayList. so i just changed my class to arrayList first then i casted it back to arrayList which solved my problem.
This way. Here i coded MainActivity.class
sharedPreferences.edit().putString("places",ObjectSerializer.serialize(MainActivity.class)).apply();
Whereas it has to be MainActivity.places in following Way
sharedPreferences.edit().putString("places",ObjectSerializer.serialize(MainActivity.places)).apply();
So, here i was actually casting a class to arrayList which gave me this error. Hope any beginner will prevent this mistake from this Question.
Thanks You All...

Android intent error null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hello im new in stackover flow i want to try these website and ask for someones help in my android when i change the intent there's an error in my android monitor in android studio here is it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kim.checkerv3, PID: 2970
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kim.checkerv3/com.example.kim.checkerv3.BudgetOutput}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at com.example.kim.checkerv3.BudgetOutput.onCreate(BudgetOutput.java:22)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
i didn't understand this i'd tried researching for solution and im still stuck on it.
Here the intent will be pass to other java class.
package com.example.kim.checkerv3;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by KIM-PC on 12/5/2016.
*/
public class BudgetFragment extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_budget, container, false);
final EditText etCash = (EditText) v.findViewById(R.id.etCash);
final Button bBudget = (Button) v.findViewById(R.id.bBudget);
bBudget.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
SharedPreferences sharedpref = getContext().getSharedPreferences("user_id", MODE_PRIVATE);
String id = sharedpref.getString("user_id","");
final int budgeted = Integer.parseInt(etCash.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray arr = jsonResponse.getJSONArray("message");
boolean success = jsonResponse.getBoolean("success");
System.out.println(budgeted/arr.length());
int total = budgeted/arr.length();
if (success) {
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
getContext().startActivity(intent);
if (arr != null) {
int sum = 0;
for(int i = 0;i<arr.length();i++){
//listdata.add(arr.get(i).toString());
String money = arr.getJSONObject(i).getString("amount");
sum += Integer.parseInt(money);
}
SharedPreferences sharedPref1 = getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref1.edit();
editor.putInt("TotalSum", sum);
editor.commit();
System.out.println(sum);
//arrayAdapter.notifyDataSetChanged();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Failed to fetch. Try again.")
.setNegativeButton("OK", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RecordRequest recordRequest = new RecordRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(recordRequest);
}
});
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
SharedPreferences sharedpref1 = getContext().getSharedPreferences("mypref", MODE_PRIVATE);
int budgeted = sharedpref1.getInt("TotalSum", 0);
System.out.println(budgeted/2);
}
}
and the class where the intent will be get.
package com.example.kim.checkerv3;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by KIM-PC on 12/6/2016.
*/
public class BudgetOutput extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
final TextView tvOutput = (TextView) findViewById(R.id.tvoutput);
Bundle b = getIntent().getExtras();
String output=b.getString("total");
if(b !=null)
output = b.getString("total");
tvOutput.setText(output+" Per cheque record.");
}
}
if there is someone who could solve i appreciate and give my thanks to you.
Well, you forgot to add your Bundle to the Intent
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
intent.putExtras(b);
getContext().startActivity(intent);

Sending String to PHP file via android application

I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));

Choose activity dynamically during splashscreen

I'm doing a small project, and today I had to make a conditional validation in splashscreen. The project was practically finalized when we decided to do this validation in splashscreen.
Modified my class and was working ok, but I had to include the time for the splash disappears (variable SPLASH_TIME_OUT) and started giving an error that I do not understand.
My splashscreen clas (now) is:
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PesquisaVoto().execute();
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int SPLASH_TIME_OUT = 2000;
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
} else {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
The error I am getting is:
03-03 17:38:49.882 10432-10450/com.clubee.vote D/Create Response﹕ {"voto":[{"count":"1"}],"success":1}
03-03 17:38:49.882 10432-10450/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 17:38:49.892 10432-10450/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 10432
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done
Anyone knows what I did wrong? Is it possivel to implement the Runnable inside the IF statement? If I do not put the timeout variable, everything is right.
UPDATE THE LOG WITH ERROR
03-03 22:01:50.016 18731-18746/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 22:01:50.026 18731-18746/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 18731
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:87)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:48)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
03-03 22:01:50.697 18731-18731/com.clubee.vote E/WindowManager﹕ android.view.WindowLeaked: Activity com.clubee.vote.Splashscreen has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{44aa2458 V.E..... R......D 0,0-681,345} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:350)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:294)
at com.clubee.vote.Splashscreen$PesquisaVoto.onPreExecute(Splashscreen.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.clubee.vote.Splashscreen.onCreate(Splashscreen.java:44)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
03-03 22:01:52.529 18731-18746/com.clubee.vote I/Process﹕ Sending signal. PID: 18731 SIG: 9
Tks in advance for answers and comments. I corrected my code, re-wrote and re-structured it, became easier to see where the mistakes were.
below, I leave the code that is working for future research. thank you very much
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static int SPLASH_TIME_OUT = 2000;
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new PesquisaVoto().execute();
}
}, SPLASH_TIME_OUT);
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
}
else {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
I cannot clearly see what is wrong based on the Logs you provided but there is something wrong with your structure.
You are starting an Activity within doInBackground Process and then dismissing the Progress Dialog which belongs to the Activity that you just finished.
Try to pass a parameter to the onPostExecute and then finish your Activity there.
And post some more details from your Log to make it clear. There has to be some more logs indicating what went wrong.

Data not retrieved from previous page, passing from intent

My app requires the data in the page to pass to another page, but apparantly, data are not passed, and I'm unsure of the error. Following is the warning code and error code.
W/System.err(18031): org.json.JSONException: No value for employ
W/System.err(18031): at org.json.JSONObject.get(JSONObject.java:354)
W/System.err(18031): at org.json.JSONObject.getJSONArray(JSONObject.java:548)
W/System.err(18031): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:138)
W/System.err(18031): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:1)
W/System.err(18031): at android.os.AsyncTask$2.call(AsyncTask.java:287)
W/System.err(18031): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
W/System.err(18031): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
W/System.err(18031): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
W/System.err(18031): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
W/System.err(18031): at java.lang.Thread.run(Thread.java:841)
E/ViewRootImpl(18031): sendUserActionEvent() mView == null
This is the code for the java class.
package com.example.splashscreentwo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class EmployeePayslip extends Activity {
private ProgressDialog pDialog;
String pid;
TextView employeeName;
TextView Desc;
TextView txtCreatedAt;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONArray payslip = null;
ArrayList<HashMap<String, String>> payslipList;
// url to get all fulltime employees list
private static String url_payslip = "http://rollit.sg/FYP/ExportPayslip.php";
private static String url_employees = "http://rollit.sg/FYP/Existing_employees_FullTime.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PAYSLIP = "payslip";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PAYSLIPNO = "payslipno";
private static final String TAG_NETSALARY = "netsalary";
private static final String TAG_ISSUEDATE = "issuedate";
private static final String TAG_STARTOFPAYSLIP = "startofpayslip";
private static final String TAG_ENDOFPAYSLIP = "endofpayslip";
private static final String TAG_TYPEOFALLOWANCE = "typeofallowance";
private static final String TAG_ALLOWANCEAMT = "allowanceamt";
private static final String TAG_ALLOWANCEDATE = "allowancedate";
private static final String TAG_AVAILABLEALLOWANCE = "availableallowance";
private static final String TAG_TYPEOFDEDUCTION = "typeofdeduction";
private static final String TAG_DEDUCTIONAMT = "deductionamt";
private static final String TAG_DEDUCTIONDATE = "deductiondate";
private static final String TAG_AGREEDOVERTIMERATE = "agreedovertimerate";
private static final String TAG_OVERTIMERATE = "overtimerate";
private static final String TAG_STARTOFOVERTIMEPERIOD = "startofovertimeperiod";
private static final String TAG_ENDOFOVERTIMEPERIOD = "endofovertimeperiod";
private static final String TAG_BASICSALARY = "basicsalary";
private static final String TAG_EXTRAPAYMENT = "extrapayment";
private static final String TAG_EMPLOYEE = "employ";
private static final String TAG_SALARY = "pay";
private static final String TAG_DESCRIPTION = "description";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.employeepayslip);
payslipList = new ArrayList<HashMap<String, String>>();
// Loading all fulltime employees in Background Thread
// getting employee details from intent
Intent i = getIntent();
// getting employee id (pid) from intent
pid = i.getStringExtra(TAG_PID);
new GetEmployeeDetails().execute();
}
class GetEmployeeDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmployeePayslip.this);
pDialog.setMessage("Loading employees details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting employee details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("pid", pid));
// getting employee details by making HTTP request
// Note that employee details url will use GET request
JSONObject json = jParser.makeHttpRequest(
url_employees, "GET", params1);
// check your log for json response
Log.d("Employee Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received employee details
JSONArray employeeObj = json
.getJSONArray(TAG_EMPLOYEE); // JSON Array
// get first employee object from JSON Array
JSONObject employee = employeeObj.getJSONObject(0);
// employee with this pid found
// Edit Text
employeeName = (TextView) findViewById(R.id.employeeName);
Desc = (TextView) findViewById(R.id.departmenttext);
// display employee data in EditText
employeeName.setText(employee.getString(TAG_NAME));
Desc.setText(employee.getString(TAG_DESCRIPTION));
}else{
// employee 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();
}
}
}
This is the code for the previous page. Data from this page are to pass to the another page above.
package com.example.splashscreentwo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllFTemployeesActivity extends ListActivity
{
LayoutInflater inflater; // Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> employeesList;
// url to get all fulltime employees list
private static String url_employees = "http://rollit.sg/FYP/Existing_employees_FullTime.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_EMPLOYEE = "employee";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray employee = null; private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ft_employees);
ImageButton ButtonPT = (ImageButton) findViewById(R.id.btnpt);
ImageButton BtnAddEmployee = (ImageButton) findViewById(R.id.addEmployeeBtn);
BtnAddEmployee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching emplopyee regstration Activity
Intent i = new Intent(getApplicationContext(), RegisterEmployeeActivity.class);
startActivity(i);
finish();
}
});
ButtonPT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All fulltime employees Activity
Intent i = new Intent(getApplicationContext(), AllPTemployeesActivity.class);
startActivity(i);
finish();
}
});
// Hashmap for ListView
employeesList = new ArrayList<HashMap<String, String>>();
// Loading all fulltime employees in Background Thread
new LoadAllEmployee().execute();
// Get listview
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View header = inflater.inflate(R.layout.planets_heade_view, null);
// lv.addHeaderView(header);
// on seleting single fulltime employee
// launching Edit single fulltime employee 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(),
EmployeePayslip.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 single fulltime employee 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 employee
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all fulltime employees by making HTTP Request
* */
class LoadAllEmployee extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
// protected void onPreExecute() {
// super.onPreExecute();
// pDialog = new ProgressDialog(AllProductsActivity.this);
// pDialog.setMessage("Loading products. Please wait...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(false);
// pDialog.show(); // } //
/**
* getting All fulltime employees 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_employees, "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) {
// fulltime employees found
// Getting Array of fulltime employees
employee = json.getJSONArray(TAG_EMPLOYEE);
// looping through All fulltime employees
for (int i = 0; i < employee.length(); i++) {
JSONObject c = employee.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String description= c.getString(TAG_DESCRIPTION);
// 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);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
employeesList.add(map);
}
} else {
// no fulltime employee found
// Launch Add New employee 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(
AllFTemployeesActivity.this, employeesList,
R.layout.list_item_ft, new String[] { TAG_PID,
TAG_NAME,TAG_DESCRIPTION},
new int[] { R.id.pid, R.id.name, R.id.description});
// updating listview
setListAdapter(adapter);
}
});
}
} }
What is wrong with the codes? Am I missing out something? If so, please guide me along, thanks and i appreciate any help given!
SO there was a spelling error with the string. After correcting the spelling in String, i got this error instead.
E/AndroidRuntime(2421): FATAL EXCEPTION: AsyncTask #4
E/AndroidRuntime(2421): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(2421): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(2421): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(2421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(2421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(2421): at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(2421): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
E/AndroidRuntime(2421): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6833)
E/AndroidRuntime(2421): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1082)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.widget.ScrollView.requestLayout(ScrollView.java:2120)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.widget.TableLayout.requestLayout(TableLayout.java:230)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.widget.TextView.checkForRelayout(TextView.java:7660)
E/AndroidRuntime(2421): at android.widget.TextView.setText(TextView.java:4446)
E/AndroidRuntime(2421): at android.widget.TextView.setText(TextView.java:4283)
E/AndroidRuntime(2421): at android.widget.TextView.setText(TextView.java:4258)
E/AndroidRuntime(2421): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:153)
E/AndroidRuntime(2421): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:1)
E/AndroidRuntime(2421): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(2421): ... 4 more
D/AbsListView(2421): onVisibilityChanged() is called, visibility : 0
D/AbsListView(2421): unregisterIRListener() is called
D/AbsListView(2421): unregisterIRListener() is called
E/WindowManager(2421): Activity com.example.splashscreentwo.EmployeePayslip has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42e528b0 V.E..... R.....ID 0,0-640,230} that was originally added here
E/WindowManager(2421): android.view.WindowLeaked: Activity com.example.splashscreentwo.EmployeePayslip has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42e528b0 V.E..... R.....ID 0,0-640,230} that was originally added here
E/WindowManager(2421): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:454)
E/WindowManager(2421): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
E/WindowManager(2421): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
E/WindowManager(2421): at android.app.Dialog.show(Dialog.java:287)
E/WindowManager(2421): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.onPreExecute(EmployeePayslip.java:111)
E/WindowManager(2421): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
E/WindowManager(2421): at android.os.AsyncTask.execute(AsyncTask.java:534)
E/WindowManager(2421): at com.example.splashscreentwo.EmployeePayslip.onCreate(EmployeePayslip.java:93)
E/WindowManager(2421): at android.app.Activity.performCreate(Activity.java:5372)
E/WindowManager(2421): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
E/WindowManager(2421): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
E/WindowManager(2421): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
E/WindowManager(2421): at android.app.ActivityThread.access$700(ActivityThread.java:168)
E/WindowManager(2421): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
E/WindowManager(2421): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(2421): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(2421): at android.app.ActivityThread.main(ActivityThread.java:5493)
E/WindowManager(2421): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(2421): at java.lang.reflect.Method.invoke(Method.java:525)
E/WindowManager(2421): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
E/WindowManager(2421): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
E/WindowManager(2421): at dalvik.system.NativeStart.main(Native Method)
Instead of following in EmployeePayslip
// Loading all fulltime employees in Background Thread
// getting employee details from intent
Intent i = getIntent();
// getting employee id (pid) from intent
pid = i.getStringExtra(TAG_PID);
give a try with following
Bundle extras = getIntent().getExtras();
if (extras != null)
{
pid = extras.getString(TAG_PID);
}
Edited: Seems #user666 is correct. First correct the spelling of TAG_EMPLOYEE in both classes as follow:
private static final String TAG_EMPLOYEE = "employee";

Categories

Resources