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]);
}
}
}
Related
I have a problem with AsyncTask in my app. AsyncTask is located in SplashScreenAcivity.java. It downloads data using json for MainActivity.java while showing splash screen. When data is loaded, app shows MainActivity screen. However, when i turn off internet connection app crashes. Instead of it i would like to move to MainActivity.java and show toast that internet connection must be turned on. SplashScreen.java loads data for listView in MainActivity.
SplashActivityScreen.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new DownloadData().execute();
}
private class DownloadData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
SyncHttpClient clientOne = new SyncHttpClient();
clientOne.get("https://api.themoviedb.org/3/tv/top_rated?api_key=d253f520df9cd868af7db8daaa0db8fb&language=en-US", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
tvseries0 = response.getJSONArray("results").getJSONObject(0).getString("name");
tvseries1 = response.getJSONArray("results").getJSONObject(1).getString("name");
tvseries2 = response.getJSONArray("results").getJSONObject(2).getString("name");
tvseries3 = response.getJSONArray("results").getJSONObject(3).getString("name");
tvseries4 = response.getJSONArray("results").getJSONObject(4).getString("name");
tvseries5 = response.getJSONArray("results").getJSONObject(5).getString("name");
tvseries6 = response.getJSONArray("results").getJSONObject(6).getString("name");
tvseries7 = response.getJSONArray("results").getJSONObject(7).getString("name");
tvseries8 = response.getJSONArray("results").getJSONObject(8).getString("name");
tvseries9 = response.getJSONArray("results").getJSONObject(9).getString("name");
tvseries10 = response.getJSONArray("results").getJSONObject(10).getString("name");
tvseries11 = response.getJSONArray("results").getJSONObject(11).getString("name");
tvseries12 = response.getJSONArray("results").getJSONObject(12).getString("name");
tvseries13 = response.getJSONArray("results").getJSONObject(13).getString("name");
tvseries14 = response.getJSONArray("results").getJSONObject(14).getString("name");
tvseries15 = response.getJSONArray("results").getJSONObject(15).getString("name");
tvseries16 = response.getJSONArray("results").getJSONObject(16).getString("name");
tvseries17 = response.getJSONArray("results").getJSONObject(17).getString("name");
tvseries18 = response.getJSONArray("results").getJSONObject(18).getString("name");
tvseries19 = response.getJSONArray("results").getJSONObject(19).getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers,Throwable e , JSONObject response) {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("tvseries0", tvseries0);
i.putExtra("tvseries1", tvseries1);
i.putExtra("tvseries2", tvseries2);
i.putExtra("tvseries3", tvseries3);
i.putExtra("tvseries4", tvseries4);
i.putExtra("tvseries5", tvseries5);
i.putExtra("tvseries6", tvseries6);
i.putExtra("tvseries7", tvseries7);
i.putExtra("tvseries8", tvseries8);
i.putExtra("tvseries9", tvseries9);
i.putExtra("tvseries10", tvseries10);
i.putExtra("tvseries11", tvseries11);
i.putExtra("tvseries12", tvseries12);
i.putExtra("tvseries13", tvseries13);
i.putExtra("tvseries14", tvseries14);
i.putExtra("tvseries15", tvseries15);
i.putExtra("tvseries16", tvseries16);
i.putExtra("tvseries17", tvseries17);
i.putExtra("tvseries18", tvseries18);
i.putExtra("tvseries19", tvseries19);
startActivity(i);
finish();
}
}
}
Crash 1
04-30 13:15:35.165 12349-12365/przemo.me.recommend.recommendme E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: przemo.me.recommend.recommendme, PID: 12349
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
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: java.lang.RuntimeException: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
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)
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:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
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)
Crash 2
04-30 13:15:35.162 12349-12365/przemo.me.recommend.recommendme E/AsyncHttpRH: User-space exception detected!
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:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
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)
You can not do UI operations from non UI thread. Like in your code you are showing Toast in Async task thread.
You should replace
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
with this
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
use -
SplashScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
Here is a server connection AsyncTask task that I created years ago in Android Java. The background task works successfully. I used it to update in the background the data repository in the App I developed at that time.
public class DataExchangeStore extends Application {
public void startServerConnection(Context contextGlobal, Activity activityGlobal) {
this.contextGlobal = contextGlobal;
this.activityGlobal = activityGlobal;
connectTask = new ConnectTask();
connectTask.execute("");
}
private ConnectTask connectTask;
public class ConnectTask extends AsyncTask<String, String, TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_BACKGROUND);
// we create a TCPClient object
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
// here the messageReceived method is implemented
public void messageReceived(ChatMessage message) {
// this method calls the onProgressUpdate
publishProgress(message.getMessage());
}
}, contextGlobal, activityGlobal);
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
System.err.println(values[0]);
// do your stuff here
}
}
Import is to permanently lock the screen orientation of the activity, specifying the screenOrientation attribute in the Android-Manifest file with portrait or landscape values:
<activity android:screenOrientation="portrait" />
Although previous answers are not wrong, using runOnUiThread() to jump out of the background thread in the AsyncTask is not a good practice. You have the onPostExecute() method for that.
What you should be doing is passing a result object to onPostExecute(). This object would encapsulate the result state (ie: error or success) and the actual data received. Then in onPostExecute() you check the result state and display a Toast if the state is error.
And do yourself a favor and replace your 20 TvSerie objects by a List<TvSerie> and do a loop in you AsyncTask to populate the list.
Please refer to the AsyncTask documentation for details on how to properly use it.
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.
I've recently been using a tutorial to develop CRUD operations for my android application. The classes contain no errors and the app syncs with my localhost. However, when I want to click a button to view all my user profiles, I get a blank screen but my logCat shows a success message?
Please help!
Class which controls the viewing:
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AllProfile extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> profileList;
// url to get all products list
private static String url_all_profile = "http://MYIPADDRESS:8888/android_connect/get_all_profiles.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERPROFILE = "userprofile";
private static final String TAG_PID = "pid";
private static final String TAG_FIRSTNAME = "firstname";
// products JSONArray
JSONArray userprofile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_profile);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProfile().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProfile.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProfile extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProfile.this);
pDialog.setMessage("Loading profiles. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_USERPROFILE);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String pid = c.getString(TAG_PID);
String firstname = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, pid);
map.put(TAG_FIRSTNAME, firstname);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
AddProfile.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(
AllProfile.this, profileList,
R.layout.list_item, new String[] { TAG_PID,
TAG_FIRSTNAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
My php is working as i've debugged it and tested it on HTML and it displays what I want.
logCAT:
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme D/All Profiles:﹕ {"success":1,"UserProfile":[{"updated_at":"0000-00-00 00:00:00","address":"Tottenham Hale","age":"21","created_at":"2015-02-04 21:22:09","gender":"Male","lastname":"Sharma","pid":"4","firstname":"Ankhit","comments":"Help Me"}]}
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ org.json.JSONException: No value for userprofile
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:544)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at com.example.ankhit.saveme.AllProfile$LoadAllProfile.doInBackground(AllProfile.java:144)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at com.example.ankhit.saveme.AllProfile$LoadAllProfile.doInBackground(AllProfile.java:110)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
02-04 22:11:59.199 20039-20039/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
02-04 22:11:59.199 20039-20039/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
02-04 22:11:59.209 20039-20039/com.example.ankhit.saveme E/ViewRootImpl﹕ sendUserActionEvent() mView == null
My list view files have no errors. add_profile has a list view with id/list and list_item has two textviews with id/pid and id/name respectively. Any thoughts?
You do not parse the JSON correctly.
"UserProfile" != "userprofile"
To get the values from the JSON, you must use the appropriate keys. Because you use the incorrect keys, org.json.JSONException is thrown, and most of the time, you should take care of thrown exceptions. :)
You need to change this:
private static final String TAG_USERPROFILE = "userprofile";
to
private static final String TAG_USERPROFILE = "UserProfile";
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>
Ok - so I'm using the following tutorial: "How to connect Android with PHP, MySQL"
However almost everyone who attempts the tutorial (judging from the comments) is having force close issues due to the application only being designed to run on API level 8 or earlier.
Several users have developed a fix for this involving adding the following lines of code in EditProductActivity.java file
// this part only to identify where to put the working code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// NB * insert the line below in import section of EditProductActivity.java
// import android.os.StrictMode;
// Now the code thaat avoid the NetworkOnMainThreadException error
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
However I'm getting messages in my logcat stating StrictMode cannot be resolved and StrictMode cannot be resolved to a type. I've done a bit of research into this and StrictMode is included in API level 8 and above. Taking that into consideration I've raised my API levels in AndroidManifest.xml to:
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="9"/>
Then cleaned my project - however I still get StrictMode cannot be resolved to a type errors.
LOGCAT:
03-17 14:06:57.924: D/AndroidRuntime(18472): Shutting down VM
03-17 14:06:57.924: W/dalvikvm(18472): threadid=1: thread exiting with uncaught exception (group=0x41604930)
03-17 14:06:57.924: E/AndroidRuntime(18472): FATAL EXCEPTION: main
03-17 14:06:57.924: E/AndroidRuntime(18472): java.lang.Error: Unresolved compilation problems:
03-17 14:06:57.924: E/AndroidRuntime(18472): The import android.os.StrictMode cannot be resolved
03-17 14:06:57.924: E/AndroidRuntime(18472): StrictMode cannot be resolved to a type
03-17 14:06:57.924: E/AndroidRuntime(18472): StrictMode cannot be resolved to a type
03-17 14:06:57.924: E/AndroidRuntime(18472): StrictMode cannot be resolved
03-17 14:06:57.924: E/AndroidRuntime(18472): at com.example.androidhive.NewProductActivity.<init>(NewProductActivity.java:10)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.Class.newInstanceImpl(Native Method)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.Class.newInstance(Class.java:1319)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.os.Looper.loop(Looper.java:137)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 14:06:57.924: E/AndroidRuntime(18472): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 14:06:57.924: E/AndroidRuntime(18472): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 14:06:57.924: E/AndroidRuntime(18472): at dalvik.system.NativeStart.main(Native Method)
JAVA:
import java.util.ArrayList;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.StrictMode;
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://linkingmanager.zxq.net/get_product_details.php";
// url to update product
private static final String url_update_product = "http://linkingmanager.zxq.net/update_product.php";
// url to delete product
private static final String url_delete_product = "http://linkingmanager.zxq.net/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} 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 uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair> ();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} 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();
}
}
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Since you are using AsyncTask there is no need to setting ThreadPolicy.And don't forget that StrictMode is available starting with 2.3 version.
Update:
Your app is not designated very well. Look at this
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
...
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
...
}
}
Why you're doing that? doInBackground() is directly designed for performing background operations also already runs on background Thread and you shouldn't perform UI update from it. You shouldn't mix it.
If you want to update UI, AsyncTask offers proper methods for achieve it:
onPreExecute()
onProgressUpdate()
onPostExecute()
Hence if you want to update your UI with some information about progress of background task call publishProgress(<data>) method that automatic invokes onProgressUpdate() method and from its update UI.
In your case you are performing initialisation of UI elements in doInBackground() method that you shouldn't.
I suggest you to make this:
Initialise your widgets in onCreate() method.
When you want to update them with data retrieved from
doInBackground() method, call publishProgress() that invoke
onProgressUpdate() method and here perform updating
Here is example:
#Override
protected void onProgressUpdate(String... params) {
txtName.setText(<value>);
...
}
Based on things mentioned above i guess that you need to read AsyncTask tutorial:
So check this
link
Just make sure both your server and the android device is connected to the same wifi connection,make changes in the ip address as your server address for eg: change it to 192.168.1.102(whatever is shown on your server
The code works well and good i have tried it