Error with ArrayAdapter in AsyncTask - java

I have the following code but I get an error on this line “userSpinner.setAdapter(adapter);”
private class Task extends AsyncTask<Void, Void, Void>
{
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... JSONArray) {
try
{
HttpGet request = new HttpGet(SERVICE_URI + "/GetBusNames");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject jsonResponse = new JSONObject(new String(buffer));
JSONArray myUsers = jsonResponse.getJSONArray("GetBusNamesResult");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
}
}
The following is the Stack Trace produced,
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): FATAL EXCEPTION: AsyncTask #1
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.AsyncTask$3.done(AsyncTask.java:200)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.lang.Thread.run(Thread.java:1096)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.Handler.<init>(Handler.java:121)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.widget.Toast.<init>(Toast.java:68)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.widget.Toast.makeText(Toast.java:231)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity.displayExceptionMessage(RealestateActivity.java:271)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity$Task.doInBackground(RealestateActivity.java:131)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity$Task.doInBackground(RealestateActivity.java:1)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.AsyncTask$2.call(AsyncTask.java:185)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): ... 4 more
11-07 19:56:22.714: ERROR/PowerManagerService(2464): CurLock p:3 mPS:1
11-07 20:06:26.577: ERROR/libnetutils(2464): dhcp start cmd 11 : [dhcpcd:-ABK]
11-07 20:06:27.054: ERROR/HierarchicalStateMachine(2464): TetherMaster - unhandledMessage: msg.what=3
The code works in its own method but not in the AsyncTask.
Any idea’s.
Cheers,
Mike.

You can't perform Display/Update UI inside the doInBackground() method, instead either you can perform by implement runOnUIThread() method or write display/Update statement inside the onPostExecute() method.
In your case, write below statement inside the onPostExecute() and declare JSONArray myUsers at class level:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
Final Solution:
private class Task extends AsyncTask<Void, Void, Void>
{
JSONArray myUsers = null;
JSONObject jsonResponse = null; // this is also needed at class level
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... JSONArray) {
try
{
HttpGet request = new HttpGet(SERVICE_URI + "/GetBusNames");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
jsonResponse = new JSONObject(new String(buffer));
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
myUsers = jsonResponse.getJSONArray("GetBusNamesResult");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}

Use below code inside your onPostExecute method.
userSpinner.setAdapter(adapter);
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
Try this it may help you..

you need to move all the UI manipulation into postExecute method which is executed in the main app thread. Android UI is not thread safe.

Don't do UI related tasks in doInBackground(). Collect your data in doInBackground() and return i from there. Get your data as a parameter to onPostExecute() and issue your userSpinner.* calls there.

Related

Android - Error when uploading multiple images

I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
return responseString;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).

Insert into database AsyncTask error

I make an android application on movies. I have a database movies. In the application I display the movies in ListView and I add a new movie.
I have a problem when I try to insert in my dataBase a new movie. Indeed, I have n error in my AsyncTask in the doInBackground but I don't know why. When I use the debugger, I have reject on the begin of the doInBackground at the line :
String title = eTitle.getText().toString();
So I give you my java code :
public class AddMovie extends Activity implements OnClickListener{
// Edit and Button that the user fill
private EditText eTitle, eActors, eDirector, eKind, eDate, eImage, eSummary ;
private Button bAdd;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
//JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
eTitle = (EditText)findViewById(R.id.title);
eActors = (EditText)findViewById(R.id.actors);
eDirector = (EditText)findViewById(R.id.director);
eKind = (EditText)findViewById(R.id.kind);
eDate = (EditText)findViewById(R.id.date);
eImage = (EditText)findViewById(R.id.image);
eSummary = (EditText)findViewById(R.id.summary);
bAdd = (Button)findViewById(R.id.addMovies);
bAdd.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.addMovies:
new AttempMovie().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}
class AttempMovie extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddMovie.this);
pDialog.setMessage("Attempting for add new movie...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
try {
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("title", title));
params.add(new BasicNameValuePair("actors", actors));
params.add(new BasicNameValuePair("director", director));
params.add(new BasicNameValuePair("kind", kind));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("image", image));
params.add(new BasicNameValuePair("summary", summary));
Log.d("request!", "starting");
JSONObject json = JSONfunctions.getJSONfromURL("http://10.0.0.35/BD_Enterprise_Mobility_Movies/add_movie.php");
// checking log for json response
Log.d("Register attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Log.d("Successfully Register!", json.toString());
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;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Intent i = new Intent(AddMovie.this,MainActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(i);
Toast.makeText(AddMovie.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
I give you also my JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject json = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return json;
}
}
And my error in the logcat:
03-20 18:28:19.753: E/AndroidRuntime(14656): FATAL EXCEPTION: AsyncTask #3
03-20 18:28:19.753: E/AndroidRuntime(14656): Process: com.mickKoza.jsonkoza, PID: 14656
03-20 18:28:19.753: E/AndroidRuntime(14656): java.lang.RuntimeException: An error occured while executing doInBackground()
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.lang.Thread.run(Thread.java:818)
03-20 18:28:19.753: E/AndroidRuntime(14656): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:81)
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:1)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 18:28:19.753: E/AndroidRuntime(14656): ... 4 more
03-20 18:28:20.184: E/WindowManager(14656): android.view.WindowLeaked: Activity com.mickKoza.jsonkoza.AddMovie has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3e1b7378 V.E..... R......D 0,0-1026,288} that was originally added here
03-20 18:28:20.184: E/WindowManager(14656): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.Dialog.show(Dialog.java:298)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.onPreExecute(AddMovie.java:74)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.execute(AsyncTask.java:535)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie.onClick(AddMovie.java:54)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View.performClick(View.java:4756)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View$PerformClick.run(View.java:19749)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.handleCallback(Handler.java:739)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.dispatchMessage(Handler.java:95)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Looper.loop(Looper.java:135)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Native Method)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Method.java:372)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thank you for your help
Michaël
One (or possibly all) of these views is null:
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
Possibly the view IDs that you're referencing during onCreate to find these views are not correct?

Error parsing data org.json.JSONException: Value <br with a login system android

I want to make a login registration system with my app but is not working properly. Here the code where I think I've got an error.
PHP LOGIN SCRIPT :
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
$response["message"] = "Enter username and password!";
die(json_encode($response));
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
<?php
?>
LoginActivity :
public class LoginActivity extends ActionBarActivity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_MESSAGE = "message";
// Testing on emulator
private static String LOGIN_URL = "http://10.0.2.2/webservice/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new LoginProcess().execute();
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
private class LoginProcess extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// Check for success tag
int success;
String username = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(KEY_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginActivity.this,
MainActivity.class);
finish();
startActivity(i);
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(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
Log.d("JSON Parser", json);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
When I want to login with the right username and password it's working but if I put right username and wrong password I've got an error. But if I delete query_params at :
$result = $stmt->execute($query_params);
I don't have any errors but I can't login anymore
The logcat :
08-31 10:40:39.885: E/Trace(1239): error opening trace file: No such file or directory (2)
08-31 10:40:40.785: D/dalvikvm(1239): GC_FOR_ALLOC freed 118K, 2% free 10936K/11143K, paused 55ms, total 57ms
08-31 10:40:40.845: I/dalvikvm-heap(1239): Grow heap (frag case) to 13.346MB for 2764816-byte allocation
08-31 10:40:40.954: D/dalvikvm(1239): GC_CONCURRENT freed 1K, 2% free 13635K/13895K, paused 24ms+6ms, total 108ms
08-31 10:40:41.334: D/libEGL(1239): loaded /system/lib/egl/libEGL_emulation.so
08-31 10:40:41.345: D/(1239): HostConnection::get() New Host Connection established 0x2a126450, tid 1239
08-31 10:40:41.357: D/libEGL(1239): loaded /system/lib/egl/libGLESv1_CM_emulation.so
08-31 10:40:41.376: D/libEGL(1239): loaded /system/lib/egl/libGLESv2_emulation.so
08-31 10:40:41.455: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:41.465: D/OpenGLRenderer(1239): Enabling debug mode 0
08-31 10:40:45.545: D/request!(1239): starting
08-31 10:40:45.645: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:48.205: E/JSON Parser(1239): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
08-31 10:40:48.355: W/dalvikvm(1239): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
08-31 10:40:48.754: E/AndroidRuntime(1239): FATAL EXCEPTION: AsyncTask #1
08-31 10:40:48.754: E/AndroidRuntime(1239): java.lang.RuntimeException: An error occured while executing doInBackground()
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.lang.Thread.run(Thread.java:856)
08-31 10:40:48.754: E/AndroidRuntime(1239): Caused by: java.lang.NullPointerException
08-31 10:40:48.754: E/AndroidRuntime(1239): at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:118)
08-31 10:40:48.754: E/AndroidRuntime(1239): at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:1)
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-31 10:40:48.754: E/AndroidRuntime(1239): ... 5 more
08-31 10:40:51.844: E/WindowManager(1239): Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): android.view.WindowLeaked: Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.Window$LocalWindowManager.addView(Window.java:547)
08-31 10:40:51.844: E/WindowManager(1239): at android.app.Dialog.show(Dialog.java:277)
08-31 10:40:51.844: E/WindowManager(1239): at com.example.diycenter.LoginActivity$LoginProcess.onPreExecute(LoginActivity.java:96)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.AsyncTask.execute(AsyncTask.java:534)
08-31 10:40:51.844: E/WindowManager(1239): at com.example.diycenter.LoginActivity$1.onClick(LoginActivity.java:69)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.View.performClick(View.java:4084)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.View$PerformClick.run(View.java:16966)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Handler.handleCallback(Handler.java:615)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Looper.loop(Looper.java:137)
08-31 10:40:51.844: E/WindowManager(1239): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-31 10:40:51.844: E/WindowManager(1239): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 10:40:51.844: E/WindowManager(1239): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 10:40:51.844: E/WindowManager(1239): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-31 10:40:51.844: E/WindowManager(1239): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 10:40:51.844: E/WindowManager(1239): at dalvik.system.NativeStart.main(Native Method)
The OP wrote in an edit:
UPDATE : I found the solution I add :
Log.e("jsonlol", json);
in the JSONParser class before i create the JSONObject and then i check in the logcat what was the the message and it was like that :
08-31 12:31:16.854: E/jsonlol(786): <br />
08-31 12:31:16.854: E/jsonlol(786): <b>Notice</b>: Undefined variable: login_ok in <b>C:\xampp\htdocs\webservice\login.php</b> on line <b>54</b><br />
08-31 12:31:16.854: E/jsonlol(786): {"success":0,"message":"Invalid Credentials!"}
08-31 12:31:17.012: E/JSON Parser(786): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
So I went to the php file login.php on line 54 and there was a variable name problem I just change
$validated_info = false;
by
$login_ok = false;
If you follow the mybringback tutorial it's an error on the script.

Using webAPIs in android for login gives FATAL EXCEPTION: AsyncTask #1 error

I am very new in using JSON in Android. I have got the webAPI that the base URL is
Test server. While developing, I am trying to login using email and password from web server database.
A user token is calculated by following formula:
Token = MD5(email + userId); I do not know what is this. What I tried to do is ;
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
System.out.println("url:: "+url );
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
//Making HTTP request
try{
//check for the request method
if(method == "POST"){
//request method to post
//default HTTPClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
//request method to GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Login.java
public class Login extends Activity {
EditText inputEmail;
EditText inputPassword;
Button loginBtn;
// Progress Dialog
ProgressDialog pDialog;
// JSONParser class
JSONParser jsonParser = new JSONParser();
// PHP Login Script location
private static final String LOGIN_URL = "http://www.sthng.com/ws/?c=profile&func=login";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "Success";
private static final String TAG_MESSAGE = "Message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
loginBtn = (Button) findViewById(R.id.btnLogin);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
});
}
// AsyncTask is a seperate thread than the thread that runs the GUI
// Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, Void, String> {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//params.add(new BasicNameValuePair("RegistrationID", ));
// Log.d("HERE", email);
// Log.d("HERE2", password);
Log.d("request!", "starting");
// getting users details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
Log.d("DEBUG!", "CHECKPOINT");
// json = json.toString();
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
/* Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);*/
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) {
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But I am getting error like;
04-29 19:03:22.691: D/request!(15060): starting
04-29 19:03:22.736: D/dalvikvm(15060): GC_CONCURRENT freed 222K, 14% free 9575K/11015K, paused 13ms+22ms, total 82ms
04-29 19:03:22.781: W/dalvikvm(15060): threadid=11: thread exiting with uncaught exception (group=0x41d082a0)
04-29 19:03:22.791: E/AndroidRuntime(15060): FATAL EXCEPTION: AsyncTask #1
04-29 19:03:22.791: E/AndroidRuntime(15060): java.lang.RuntimeException: An error occured while executing doInBackground()
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.lang.Thread.run(Thread.java:856)
04-29 19:03:22.791: E/AndroidRuntime(15060): Caused by: java.lang.IllegalArgumentException: Host name may not be null
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:519)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.JSONParser.makeHttpRequest(JSONParser.java:125)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:106)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:1)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:03:22.791: E/AndroidRuntime(15060): ... 5 more
04-29 19:03:32.686: I/Choreographer(15060): Skipped 589 frames! The application may be doing too much work on its main thread.
04-29 19:03:33.256: E/WindowManager(15060): Activity com.example.sthng.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): android.view.WindowLeaked: Activity com.example.clipme.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.Dialog.show(Dialog.java:277)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$AttemptLogin.onPreExecute(Login.java:87)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.execute(AsyncTask.java:534)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$1.onClick(Login.java:61)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View.performClick(View.java:4232)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View$PerformClick.run(View.java:17298)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.handleCallback(Handler.java:615)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Looper.loop(Looper.java:137)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.ActivityThread.main(ActivityThread.java:4921)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
04-29 19:03:33.256: E/WindowManager(15060): at dalvik.system.NativeStart.main(Native Method)
I am sure I have done some stupid mistake but please do not take it bad way. I hope I get some hints and solutions for this.
You are accessing UI element doInBackground()
Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);
above method on doInBackground(). You have to call this method onPostExecute.
you are sending email and password two time.
You make url with https:sthng.com/ws?function=login&email=" + email+ "&password=" + password
JSONObject json = jsonParser.makeHttpRequest(
"https:sthng.com/ws?function=login&email=" + email
+ "&password=" + password, "POST", params);
or
Now you make below param.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("androidToken", androidToken));// your token
and passing again
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));// passing again

Gson and Google

I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Categories

Resources