Choose activity dynamically during splashscreen - java

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.

Related

Android JSON Parsing Crashing Application AsyncTask

I am using a JSON parser to read the data from my JSON file and display it within my app, I was originally using this code to create arrays which works fine but now I have pasted it into a new application to make it get data from the JSON and put it onto a text field which isn't working. I will post the code and error log below.
package com.example.curtisboylan.myapplication;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TechnicianProfile extends AppCompatActivity {
private static String url;
private String TAG = SearchScreen.class.getSimpleName();
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_technician_profile);
Bundle bundle = getIntent().getExtras();
String username = bundle.getString("username");
String userid = bundle.getString("userid");
setTitle("Technician - " + username);
url = "http://curtisboylan.me/mygeek/mygeekprofile.php?user=" + userid;
Log.d("test", url);
new GetProfile().execute();
}
private class GetProfile extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TechnicianProfile.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("MyGeek");
TextView usernametext;
// looping through All Contacts
JSONObject c = contacts.getJSONObject(0);
usernametext = (TextView) TechnicianProfile.this.findViewById(R.id.abouttext);
usernametext.setText(c.getString("name"));
// username.add(c.getString("name"));
// userid.add(c.getString("id"));
// location.add(c.getString("location"));
// reviewscore.add(c.getString("reviewscore"));
// price.add(c.getString("price"));
// urllist.add(c.getString("url"));
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
}
}
D/test: http://curtisboylan.me/mygeek/mygeekprofile.php?user=1
E/EGL_emulation: tid 2593: eglSurfaceAttrib(1174): error 0x3009
(EGL_BAD_MATCH) W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on
surface 0x91199f00, error=EGL_BAD_MATCH E/EGL_emulation: tid 2593:
eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH) W/OpenGLRenderer:
Failed to set EGL_SWAP_BEHAVIOR on surface 0x8f2f5000,
error=EGL_BAD_MATCH E/SearchScreen: Response from url:
{"MyGeek":[{"id":"1","name":"Curtis Boylan","location":"Swords, Co
Dublin","reviewscore":"5.6","url":"https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-9/11062691_831452480236559_1123476984274233173_n.jpg?oh=8eb4bb9519a2cd3b96b085146b0ae718&oe=596BBB5F","price":"30"}]}
--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.curtisboylan.myapplication, PID: 2416
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6891)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1083)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5205)
at android.view.View.invalidateInternal(View.java:13656)
at android.view.View.invalidate(View.java:13620)
at android.view.View.invalidate(View.java:13604)
at android.widget.TextView.checkForRelayout(TextView.java:7347)
at android.widget.TextView.setText(TextView.java:4480)
at android.widget.TextView.setText(TextView.java:4337)
at android.widget.TextView.setText(TextView.java:4312)
at com.example.curtisboylan.myapplication.TechnicianProfile$GetProfile.doInBackground(TechnicianProfile.java:72)
at com.example.curtisboylan.myapplication.TechnicianProfile$GetProfile.doInBackground(TechnicianProfile.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761)  E/EGL_emulation: tid 2593: eglSurfaceAttrib(1174): error 0x3009
(EGL_BAD_MATCH) W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on
surface 0x8f2f5080, error=EGL_BAD_MATCH E/WindowManager:
android.view.WindowLeaked: Activity
com.example.curtisboylan.myapplication.TechnicianProfile has leaked
window DecorView#415df5e[] that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:322)
at com.example.curtisboylan.myapplication.TechnicianProfile$GetProfile.onPreExecute(TechnicianProfile.java:48)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:620)
at android.os.AsyncTask.execute(AsyncTask.java:567)
at com.example.curtisboylan.myapplication.TechnicianProfile.onCreate(TechnicianProfile.java:36)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
E/WindowManager: android.view.WindowLeaked: Activity
com.example.curtisboylan.myapplication.TechnicianListView has leaked
window DecorView#b6a1d55[] that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:322)
at com.example.curtisboylan.myapplication.TechnicianListView$GetContacts.onPreExecute(TechnicianListView.java:78)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:620)
at android.os.AsyncTask.execute(AsyncTask.java:567)
at com.example.curtisboylan.myapplication.TechnicianListView.initViews(TechnicianListView.java:67)
at com.example.curtisboylan.myapplication.TechnicianListView.onCreate(TechnicianListView.java:48)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You can not do any UI operation in doInBackground.
Put set text related stuff in onPostExecutemethod of AsyncTask
#Override
protected void onPostExecute(Void aVoid) {
}
remove UI component from doInBackground and update UI in postExecute method of Asynctask
You are trying to modify a View from a background thread.
View Android UI in not thread safe, and so can only be modified from the main thread.
The offence is this line in your doInBackground()
usernametext.setText(c.getString("name"));
Instead, you should return the found String from the doInBackground, override onPostExecute and set it there.
An other option is wrap is in a runOnUiThread() but honestly that's more complicated and unnecessary in this case.
You cannot use
usernametext = (TextView) TechnicianProfile.this.findViewById(R.id.abouttext);
usernametext.setText(c.getString("name"));
from .doInbackground() method, because this method is executed on background thread, but UI elements can only be changed from a main thread.
Move UI update to .onPostExecute() method.
As the error suggest "Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException" you are doing wrong thing in wrong thread. Please move your setText code to onPostExecute.
You have to use publishProgress and onProgressUpdate.
package com.example.curtisboylan.myapplication;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TechnicianProfile extends AppCompatActivity {
private static String url;
private String TAG = SearchScreen.class.getSimpleName();
private ProgressDialog pDialog;
private TextView usernametext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_technician_profile);
usernametext = (TextView) TechnicianProfile.this.findViewById(R.id.abouttext);
Bundle bundle = getIntent().getExtras();
String username = bundle.getString("username");
String userid = bundle.getString("userid");
setTitle("Technician - " + username);
url = "http://curtisboylan.me/mygeek/mygeekprofile.php?user=" + userid;
Log.d("test", url);
new GetProfile(usernametext).execute();
}
private class GetProfile extends AsyncTask<Void, String, Void> {
private TextView tv;
public GetProfile(TextView tv) {
this.tv = tv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TechnicianProfile.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("MyGeek");
// looping through All Contacts
JSONObject c = contacts.getJSONObject(0);
String str = c.getString("name");
publishProgress(str);
// username.add(c.getString("name"));
// userid.add(c.getString("id"));
// location.add(c.getString("location"));
// reviewscore.add(c.getString("reviewscore"));
// price.add(c.getString("price"));
// urllist.add(c.getString("url"));
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
tv.setText(values[0]);
}
}
}

Trigger AsyncTask from listener - AndroidStudio 1.2.2 - java.lang.NoClassDefFound

I have this interface on my Android project:
package com.kkoci.shairlook;
/**
* Created by kristian on 07/07/2015.
*/
public interface OnTaskFinishListener{
void onFinish();
}
I'm using this, to call a onPostExecute on my AsyncTask class:
package com.kkoci.shairlook;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Created by kristian on 04/07/2015.
*/
public class EndpointsAsyncTaskInsert extends AsyncTask<String, Void, User> implements GoogleClientRequestInitializer {
private static UserEndpoint myApiService = null;
private Context context;
private OnTaskFinishListener listener;
EndpointsAsyncTaskInsert(Context context) {
this.context = context;
}
public EndpointsAsyncTaskInsert(OnTaskFinishListener listener){
this.listener = listener;
}
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
// put it here no in MyClass
abstractGoogleClientRequest.setDisableGZipContent(true);
}
#Override
protected User doInBackground(String... params) {
User response = null;
if (myApiService == null) { // Only do this once
UserEndpoint.Builder builder = new UserEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("https://shairlook1.appspot.com/_ah/api/")
.setGoogleClientRequestInitializer(this);
// end options for devappserver
myApiService = builder.build();
}
try {
User users = new User();
users.setEmail(params[0]);
users.setPassword(params[1]);
users.setName(params[2]);
response = myApiService.insertUser(users).execute();
} catch (Exception e) {
Log.d("Could not Add User", e.getMessage(), e);
}
return response;
}
protected void onPostExecute(User user){
listener.onFinish();
}
}
But this is giving me java.lang.NoCalssDefFound error, I'm initializing it in my Activity like this:
public class LoginMember extends Activity implements OnTaskFinishListener {
public void onFinish(){
Intent intent = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(intent);
}
Then execute:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtEmail.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
String password = txtPassword.getText().toString();
String email = txtEmail.getText().toString();
if ((txtEmail.length() == 0) || (txtPassword.length() == 0)) {
Toast.makeText(LoginMember.this, "You need to provide values for Email and Password", Toast.LENGTH_SHORT).show();
return;
}
//Go ahead and perform the transaction
String[] params = {email, password};
new EndpointsAsyncTaskInsert(currentActivity.getApplicationContext()).execute(params);
}
});
So, the problem arises when executing EndpointAsyncTaskInsert method listener.OnFinish();
This is the complete logcat:
7752-7752/com.kkoci.shairlook E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.kkoci.shairlook.EndpointsAsyncTaskInsert.onPostExecute(EndpointsAsyncTaskInsert.java:74)
at com.kkoci.shairlook.EndpointsAsyncTaskInsert.onPostExecute(EndpointsAsyncTaskInsert.java:24)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
I've seen this question here, seems to be the same kind of problem, but I'm not really sure about that solution.
Any ideas, please?
Thanks in advance!
The logs say the error is java.lang.NullPointerException... and it's because you're creating a EndpointsAsyncTaskInsert using the Context constructor, thus listener inside of it null... and you dereference it without checking for null in onPostExecute

How to fix application has stopped in android app when clicking another button inside main activity?

I have an app that when logged in by user the user redirects to main activity which had his personal details displayed and had two buttons to click: dashboard button redirected to his dashboard manager settings and a button log out. When logged in all is working fine showing his personal details and when I clicked dashboard button for his dashboard settings the app is unfortunately stopped. It said errors in my log cat which I can't fix with my own. I am new to Android. I searched and tried threads here in SO that has same problems with me but still can not be solved. Anybody with a great heart can help me to solve this? It's been quiet a week I'm stuck on this.
note* my dashboard button is calling another layout that contains two buttons
This is my main activity java :
package com.myapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import library.JSONParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ProfileView extends Activity implements OnClickListener{
private Button bLogout, backdashboard;
private TextView tvusername, tvfullname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject display;
//String name for my sharedpref extras
String ngalan;
// Profile JSON url
private static final String PROFILE_URL = "http://10.0.2.2/webservice/profile.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//setup textview
tvusername=(TextView)(findViewById(R.id.tvusernamedisplay));
tvfullname=(TextView)(findViewById(R.id.tvfullname));
//settup buttons
backdashboard=(Button)(findViewById(R.id.backdashboard));
bLogout=(Button)(findViewById(R.id.blogout));
//button listener
backdashboard.setOnClickListener(this);
bLogout.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras.containsKey("username")) {
ngalan = extras.getString("username");
// Loading Profile in Background Thread
new LoadProfile().execute();
}
}
#Override
public void onClick(View args) {
// TODO Auto-generated method stub
switch (args.getId()) {
case R.id.backdashboard:
Intent r = new Intent(this, Dashboard.class);
startActivity(r);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(ProfileView.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileView.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", ngalan));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
display = new JSONObject(json);
JSONArray user = display.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String idnum = jb.getString("username");
String fulname = jb.getString("lastname");
// displaying all data in textview
tvusername.setText(idnum );
tvfullname.setText(fulname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This is my Dashboard activity java another activity calls when dashboard button is clicked...
package com.myapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Dashboard extends Activity implements OnClickListener{
private Button view, manage, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
//settup buttons
manage=(Button)(findViewById(R.id.bManage));
view=(Button)(findViewById(R.id.bView));
logout=(Button)(findViewById(R.id.blogout));
//button listener
manage.setOnClickListener(this);
view.setOnClickListener(this);
logout.setOnClickListener(this);
}
#Override
public void onClick(View item) {
// TODO Auto-generated method stub
switch (item.getId()) {
case R.id.bManage:
Intent r = new Intent(this, Manage.class);
startActivity(r);
finish();
break;
case R.id.bView:
Intent l = new Intent(this, View.class);
startActivity(l);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(Dashboard.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
}
This is my log cat error message"
08-23 18:59:36.949: E/AndroidRuntime(900): FATAL EXCEPTION: main
08-23 18:59:36.949: E/AndroidRuntime(900): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
Please help me guys :(
This is the full logcat message:
Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Looper.loop(Looper.java:137)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invoke(Method.java:511)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 18:59:36.949: E/AndroidRuntime(900): at dalvik.system.NativeStart.main(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): Caused by: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at com.myapp.Dashboard.onCreate(Dashboard.java:27)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Activity.performCreate(Activity.java:5104)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-23 18:59:36.949: E/AndroidRuntime(900): ... 11 more
I guess that NPE occurs in this line: grade.setOnClickListener(this);
You don't initialize this variable anywhere.

how do i send parameters using my android app to a remote server using JSON. the code is given below

i am using a reference code for testing ,but when i run the app and click the submit button it shows "Unfortunately your app has Stopped".
Here is my java.class
package com.internship.mtslogin;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class fpasswd extends Activity implements OnClickListener{
private EditText email ;
private Button msubmit;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
private static final String LOGIN_URL ="http://xxx.xxx.x.x:1234/webservice/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_passwd);
email = (EditText)findViewById(R.id.email);
msubmit = (Button)findViewById(R.id.submit);
msubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(fpasswd.this);
pDialog.setMessage("Please wait, Registering");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String emailid = email.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", emailid));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(fpasswd.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But when i run it in a localhost it works fine.
the parameters to be send is only "email".
and url in which i am doing is real server.
i have removed the real url and put a dummy url for string passing.
Can anyone tell me what is going wrong?
here is the logcat details.
FATAL EXCEPTION: AsyncTask #3
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.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
The answer is in the error message. You are missing INTERNET permission. Add to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
well it looks like you dont have access to the internet.
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
Add this line to the AndroidMainfest.xml to enable the Internet access.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

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