This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
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:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to build an app that lets you send data over bluetooth to an
arduino. But I got stuck while creating the socket. The app keeps
crashing on startup, but I don't know why.
package de.lutherschule.bled.bluetoothled;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.icu.util.Output;
import android.support.annotation.WorkerThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bAdapter;
BluetoothDevice device;
Boolean found;
BluetoothSocket btSocket;
OutputStream outputStream;
InputStream inputStream;
public static final String DEVICE_ADRESS = "";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = "MainActvity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bAdapter = BluetoothAdapter.getDefaultAdapter();
found = false;
btSocket = null;
Log.v(TAG, "Funst");
if (bAdapter == null) {
Toast.makeText(getApplicationContext(),"Funst net",Toast.LENGTH_SHORT).show();
}
if(!bAdapter.isEnabled()) {
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
Set<BluetoothDevice> bondedDevices = bAdapter.getBondedDevices();
if(bondedDevices.isEmpty()) {
Toast.makeText(getApplicationContext(),"Muss gepaired werden",Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iter : bondedDevices) {
if(iter.getAddress().equals(DEVICE_ADRESS)) { // oder iter.getName() wenn Name bekannt muessen dann aendern
device=iter;
found=true;
break;
}
}
}
When I delete the section under this quote. The app starts just fine.
try{
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
}catch(IOException ioe){
Log.v(TAG, "socket nit erstellt");
}
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
device = bAdapter.getRemoteDevice(DEVICE_ADRESS);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket nit erstellt", Toast.LENGTH_LONG).show();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
I'd appreciate any help. By the way sorry for my formatting... I'm a newbie in creating posts.
Android Monitor:
08-27 17:56:51.857 3071-3071/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
08-27 17:56:51.857 3071-3071/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
08-27 17:56:51.857 3071-3071/? I/art: Not late-enabling -Xcheck:jni (already on)
08-27 17:56:52.086 3071-3071/de.lutherschule.bled.bluetoothled I/InstantRun: Starting Instant Run Server for de.lutherschule.bled.bluetoothled
08-27 17:56:52.288 3071-3071/de.lutherschule.bled.bluetoothled W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
[ 08-27 17:56:52.386 1162: 2146 D/ ]
HostConnection::get() New Host Connection established 0xb68aea60, tid 2146
08-27 17:56:52.429 3071-3079/de.lutherschule.bled.bluetoothled W/art: Suspending all threads took: 17.085ms
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled E/BluetoothAdapter: Bluetooth binder is null
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled V/MainActvity: Funst
08-27 17:56:52.452 3071-3071/de.lutherschule.bled.bluetoothled D/AndroidRuntime: Shutting down VM
--------- beginning of crash
08-27 17:56:52.453 3071-3071/de.lutherschule.bled.bluetoothled E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.lutherschule.bled.bluetoothled, PID: 3071
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lutherschule.bled.bluetoothled/de.lutherschule.bled.bluetoothled.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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:5254)
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 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at de.lutherschule.bled.bluetoothled.MainActivity.onCreate(MainActivity.java:59)
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:2387)
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:5254)
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)
Try to use
BluetoothDevice device = mAdapter.getRemoteDevice(address);
btsocket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Here is my code.
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
h.sendEmptyMessage(0);
} catch (IOException e) {
// TODO Auto-generated catch block
h.sendEmptyMessage(1);
e.printStackTrace();
try {
socket.close();
} catch (IOException e2) {
}
}
I am trying to build a rally Android app.I tried https://github.com/RallyTools/RallyRestToolkitForJava As given I have added the jars.
1.commons-codec-1.6.jar
2.gson-2.2.4.jar
3.httpclient-4.2.5.jar
4.org.apache.commons.logging-1.1.1.jar
5.httpcore-4.2.4.jar
My mainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import org.apache.http.HttpHost;
import org.apache.http.client.utils.URIUtils;
public class MainActivity extends AppCompatActivity
{
String host = "https://rally1.rallydev.com";
String applicationName = "Android-Rally";
RallyRestApi restApi;
Button buttonlogin;
EditText etemail,etpass;
QueryRequest qtestset;
QueryResponse response;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etemail=(EditText) findViewById(R.id.etemail);
etpass=(EditText) findViewById(R.id.etpassword);
buttonlogin=(Button) findViewById(R.id.btnlogin);
buttonlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(etemail.equals("") && etpass.equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your Rally Credentials",Toast.LENGTH_LONG).show();
}
else
{
try
{
getRally();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
qtestset = new QueryRequest("Defects");
qtestset.setLimit(1);
try
{
response = restApi.query(qtestset);
if(!response.wasSuccessful())
{
Toast.makeText(getApplicationContext(),"Login Un-Successful",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Login Successful",Toast.LENGTH_LONG).show();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
}
public RallyRestApi getRally() throws URISyntaxException {
String password = etemail.getText().toString();
String email=etpass.getText().toString();
restApi = new RallyRestApi(new URI(host), email,password);
restApi.setApplicationName(applicationName);
return restApi;
}
}
My error log
04-18 14:07:16.299 11364-11364/com.example.apetkar.rally_poc D/AndroidRuntime: Shutting down VM
04-18 14:07:16.299 11364-11364/com.example.apetkar.rally_poc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apetkar.rally_poc, PID: 11364
java.lang.NoSuchMethodError: No static method extractHost(Ljava/net/URI;)Lorg/apache/http/HttpHost; in class Lorg/apache/http/client/utils/URIUtils; or its super classes (declaration of 'org.apache.http.client.utils.URIUtils' appears in /system/framework/org.apache.http.legacy.boot.jar)
at org.apache.http.impl.client.DecompressingHttpClient.getHttpHost(DecompressingHttpClient.java:113)
at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:108)
at com.rallydev.rest.client.HttpClient.executeRequest(HttpClient.java:157)
at com.rallydev.rest.client.HttpClient.doRequest(HttpClient.java:145)
at com.rallydev.rest.client.BasicAuthClient.doRequest(BasicAuthClient.java:56)
at com.rallydev.rest.client.HttpClient.doGet(HttpClient.java:221)
at com.rallydev.rest.RallyRestApi.query(RallyRestApi.java:172)
at com.example.apetkar.rally_poc.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Can anyone help here..stuck at this for days now..Thanks
Does android run some special mobile version of java? It seems like the 4.2 http components are likely not compatible. I haven't had a chance to look into it much, but I wonder if there is a newer set of those components that are compatible with the android environment? You could try forking the RallyRestToolkitForJava repo and updating the dependencies locally to see if you can get it to run...
There's a class conflict with the included Apache HTTP jars and the ones used by native Android. I got around this by forking the Rally project and replacing Apache HTTP with OKHttp to remove the conflict. My changes are in my fork in github: https://github.com/rawslaw/RallyRestToolkitForJava
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]);
}
}
}
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"));
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.