I have developed a login and registrartion system and the code works fine when the minSDKVersion is set to 8,But when I change the minSDkVersion to higher versions say 11 or 12 the app crashes when I try to login or register.What changes should I make in the code so that i can run in higher versions.The LoginActivity.java file is as follows:
package com.example.trial;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.trial.library.DatabaseHandler;
import com.example.trial.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// 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";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
The RegisterActivity.java file is:
package com.example.trial;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.trial.library.DatabaseHandler;
import com.example.trial.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// 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";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
The logcat looks like this:
03-24 01:20:22.154: E/AndroidRuntime(1787): FATAL EXCEPTION: main
03-24 01:20:22.154: E/AndroidRuntime(1787): android.os.NetworkOnMainThreadException
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
03-24 01:20:22.154: E/AndroidRuntime(1787): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-24 01:20:22.154: E/AndroidRuntime(1787): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-24 01:20:22.154: E/AndroidRuntime(1787): at libcore.io.IoBridge.connect(IoBridge.java:112)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.net.Socket.connect(Socket.java:842)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.example.trial.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.example.trial.library.UserFunctions.loginUser(UserFunctions.java:43)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.example.trial.LoginActivity$1.onClick(LoginActivity.java:56)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.view.View.performClick(View.java:4240)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.view.View$PerformClick.run(View.java:17721)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.Handler.handleCallback(Handler.java:730)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.Handler.dispatchMessage(Handler.java:92)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.Looper.loop(Looper.java:137)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.lang.reflect.Method.invokeNative(Native Method)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.lang.reflect.Method.invoke(Method.java:525)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-24 01:20:22.154: E/AndroidRuntime(1787): at dalvik.system.NativeStart.main(Native Method)
Here you can't perform your network operation on the UI thread as of api level 11.
So for that you have to use AsyncTask or Thread.
Example of AsyncTask.
class DowloadTest extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(YourActivityName.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
};
#Override
protected String doInBackground(String... params) {
// parse your data here
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
}
}
}
and after that execute this function whenever you need it like,
new DowloadTest().execute();
For more reference go Here
// you can add your json code in async task class
class callservice extends AsyncTask<String, String, String>
{
private ProgressDialog pDialog;
String message = "";
private String result;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args)
{
// Write your json code which get data
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
if (pDialog != null)
pDialog.dismiss();
}
}
Bcoz of your SDK tools are maybe Upgrade version doesnt support.. for example you create your project in SDK min level is 8 but your android SDk version tools is APK level 19 means it may occurs so go to your SDk Folder and delete tools Folder and then Copy your cuurent version of SDk tools must be put it in your SDK Folder.
you are using low level APK version means it will generate this line bcoz you want to access high high level code in Upgrade version supported methods means this lines will shows of your methods..
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
and also set this line in your activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
or
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
thank you.
I was also facing the same problem, solution which worked for me is :
If you don't wish to use AsyncTask in your activity, try adding below snippet in your onCreate of LoginActivity.java
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
So this will save your time and effort for solving this error.
P.S. If you get error on these line after adding them to your activity, try cleaning your application. You can also try adding
#SuppressLint("NewApi")
before oncreate method. like this,
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
Hope this well help you too.
Related
I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836
When I attempt to connect to a local Database on my computer I get a list of problems.
07-31 21:29:53.036: I/System.out(1470): 1
07-31 21:29:53.046: I/System.out(1470): 2
07-31 21:29:53.106: I/System.out(1470): 3
07-31 21:29:53.326: W/EGL_emulation(1470): eglSurfaceAttrib not implemented
07-31 21:30:00.126: E/JSON(1470):{"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}n
07-31 21:30:00.126: I/System.out(1470): 4
07-31 21:30:00.156: I/System.out(1470): 5
07-31 21:30:00.156: I/System.out(1470): ERROR
07-31 21:30:00.186: W/System.err(1470): java.lang.NullPointerException
07-31 21:30:00.186: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:138)
07-31 21:30:00.196: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:1)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 21:30:00.196: W/System.err(1470): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 21:30:00.206: W/System.err(1470): at java.lang.Thread.run(Thread.java:841)
07-31 21:30:00.206: I/System.out(1470): 9
07-31 21:30:00.326: D/AndroidRuntime(1470): Shutting down VM
07-31 21:30:00.326: W/dalvikvm(1470): threadid=1: thread exiting with uncaught exception (group=0xb1a32ba8)
07-31 21:30:00.336: E/AndroidRuntime(1470): FATAL EXCEPTION: main
07-31 21:30:00.336: E/AndroidRuntime(1470): Process: com.example.skelotong, PID: 1470
07-31 21:30:00.336: E/AndroidRuntime(1470): java.lang.NullPointerException
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:184)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:1)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Handler.dispatchMessage(Handler.java:102)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Looper.loop(Looper.java:136)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invoke(Method.java:515)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-31 21:30:00.336: E/AndroidRuntime(1470): at dalvik.system.NativeStart.main(Native Method)
07-31 21:30:03.356: I/Process(1470): Sending signal. PID: 1470 SIG: 9
07-31 21:30:05.946: D/dalvikvm(1499): GC_FOR_ALLOC freed 179K, 12% free 3467K/3932K, paused 141ms, total 144ms
07-31 21:30:06.636: D/(1499): HostConnection::get() New Host Connection established 0xb8f39498, tid 1499
07-31 21:30:06.786: W/EGL_emulation(1499): eglSurfaceAttrib not implemented
07-31 21:30:06.796: D/OpenGLRenderer(1499): Enabling debug mode 0
Here is the code that I attempt to run.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegularUsercreation extends ActionBarActivity implements Runnable {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
EditText inputUsername;
EditText dateofbirth;
EditText zip;
// EditText skils;
// 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 Handler mHandler = new Handler(Looper.getMainLooper());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regular_usercreation);
}
public void clicker(View view) {
new ruc().execute((String[]) null);
}
public void ss(View view) {
Intent i = new Intent(getApplicationContext(), RegisterClass.class);
startActivity(i);
// Close Registration View
finish();
}
private class ruc extends AsyncTask<String, Integer, Boolean> {
final ProgressDialog pd = new ProgressDialog(RegularUsercreation.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setMessage("Please wait");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
System.out.println("1");
}
#Override
protected Boolean doInBackground(String... params) {
System.out.println(2);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.FullName2);
inputEmail = (EditText) findViewById(R.id.Email2);
inputPassword = (EditText) findViewById(R.id.Password2);
inputUsername = (EditText) findViewById(R.id.Username2);
dateofbirth = (EditText) findViewById(R.id.DOB2);
zip = (EditText) findViewById(R.id.ZipCode2);
btnRegister = (Button) findViewById(R.id.create2);
btnLinkToLogin = (Button) findViewById(R.id.cancel2);
registerErrorMsg = (TextView) findViewById(R.id.errormessage3);
// skils = (EditText) findViewById(R.id.skills1);
System.out.println("3");
// Register Button Click event
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String usernmae = inputUsername.getText().toString();
String birth = dateofbirth.getText().toString();
String zipcode = zip.getText().toString();
// String skills = skils.getText().toString();
UserFunction userFunction = new UserFunction();
JSONObject json = userFunction.registerUser(name, email, password,
usernmae, birth, zipcode);
System.out.println(4);
// check for login response
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
System.out.println("5");
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
System.out.println(6);
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
System.out.println("7");
return true;
} else {
System.out.println("ERROR");
// Error in registration
//registerErrorMsg
// .setText("Error occured in registration");
return false;
}
}
} catch (JSONException e) {
publishProgress(1);
e.printStackTrace();
System.out.println("9");
return false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if (values.equals(1)) {
pd.setMessage("Almost Done");
}
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == true) {
// launch dashboard
Intent dashboard = new Intent(getApplicationContext(),
HomePage.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}
if (result == false) {
registerErrorMsg.setText("Error occured in registration");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.regular_usercreation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void run() {
// TODO Auto-generated method stub
mHandler.post(new Runnable() {
public void run() {
new ruc();
ruc.execute(RegularUsercreation.this);
}
});
}
}
How can this problem be fixed and what can be done in the future to prevent this?
Also why does this happen.
from the looks of is either res is null or something's null within these lines
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
However its hard to be sure. publishProgress or getApplicationContext may have something throwing the NullPointerException as well. Try this for debugging the problem : since you're using eclipse, you can use debugger instead of println, its way more powerful. A useful tutorial. If you don't want to use the debugger, print the values instead of numbers. They'll provide much more useeful context.
I am trying to show images in grid-view using tab-swipe. But when include async-task to fetch images from json URL the app does not even starting. It just crashes and closed. Here is my code.
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GamesFragment extends Fragment {
public GamesFragment(){}
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> items;
private Button button;
static String CATEGORY = "category";
int setlimit = 6;
int tolimit = 5;
static String IMAGE = "image";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_main, container, false);
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Student Government App");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL
("http://jsonurl.com");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("wallpaper");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("category", jsonobject.getString("category"));
map.put("image", jsonobject.getString("image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
// Pass the results into ListViewAdapter.java
adapter = new GridViewAdapter(getActivity(), arraylist);
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
How can i prevent it from app crash? Any help would be be great.
Logcat:
07-03 15:22:36.692 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT- AM_ON_PAUSE_CALLED ActivityRecord{41353570 token=android.os.BinderProxy#41352cb0 {info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}}
07-03 15:22:36.707 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-PAUSE_ACTIVITY_FINISHING handled : 0 / android.os.BinderProxy#41352cb0
07-03 15:22:36.904 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.944 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.989 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.003 838-838/info.androidhive.tabsswipe E/WindowManager﹕ Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4136f300 that was originally added here
android.view.WindowLeaked: Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4136f300 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:294)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:226)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:151)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at info.androidhive.tabsswipe.GamesFragment$DownloadJSON.onPreExecute(GamesFragment.java:65)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at info.androidhive.tabsswipe.GamesFragment.onCreateView(GamesFragment.java:48)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:15264)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15264)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15264)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2161)
at android.view.View.measure(View.java:15264)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2131)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1435)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4609)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
at android.view.Choreographer.doCallbacks(Choreographer.java:567)
at android.view.Choreographer.doFrame(Choreographer.java:536)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy#41352cb0
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 1)
You should move gridview initialized in your onCreateView(...) before new DownloadJSON().execute();
gridview = (GridView) rootview.findViewById(R.id.gridViewCustom);
Change you oncreateview like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_main, container, false);
gridview = (GridView) rootView.findViewById(R.id.gridViewCustom);
new DownloadJSON().execute();
return rootView;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = null;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading , Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
super.onPreExecute();
}
change your onPostExecute this way
#Override
protected void onPostExecute(Void args) {
mProgressDialog.dismiss();
gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
// Pass the results into ListViewAdapter.java
adapter = new GridViewAdapter(getActivity(), arraylist);
gridview.setAdapter(adapter);
super.onPostExecute(arg);
}
}
You open That app in Debugging mode
and see the error in console (choose warning) and find the error and clear it
I want to access Confirmation activity from login activity. i was able to launch confirmation activity when i didn't have login and registration activity. login and registration works perfect without confirmation activity. and dashboard activity and confirmation activity works perfect without login and registration activity.
Registration Activity.
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// 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";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Login Activity:-
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// 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";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
Dashboard Activity:-
package com.example.androidhive;
import android.app.Activity;
import com.example.androidhive.ConfirmationActivity;
import com.example.androidhive.R;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.Button;
import com.example.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
private String resultString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0)
if (resultCode == RESULT_OK) {
//Use Data to get string
resultString = data.getStringExtra("RESULT_STRING");
LaunchWebView(resultString);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void LaunchWebView(String resultString)
{
WebView engine=(WebView)findViewById(com.example.androidhive.R.id.web_engine);
//engine.getSettings().setJavaScriptEnabled(true);
String[] array=resultString.split(":");
engine.getSettings().setLoadsImagesAutomatically(true);
//engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setUseWideViewPort(true);
engine.setWebChromeClient(new MyJavaScriptChromeClient());
engine.loadUrl("http://74.101.168.139/snapshot.cgi?user="+array[0]+"&pwd="+array[1]+"&count=0" + "&resolution=32"+ "&rate=6");
}
public void btnRefresh_ClicHandler(View view)
{
if(resultString!="")
LaunchWebView(resultString);
}
public void btnHome(View arg)
{
Intent intent=new Intent(this,ConfirmationActivity.class);
int result=0;
startActivityForResult(intent, result);
}
private class MyJavaScriptChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
return super.onJsAlert(view, null, message, result);
}
}
}
Confirmation Activity : -
package com.example.androidhive;
import com.example.androidhive.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class ConfirmationActivity extends Activity {
EditText txtPassword=null;
EditText txtUsername=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
}
public static final class menu2 {
public static final int confirmation=0x7f080000;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(menu2.confirmation, menu);
return true;
}
public void btnCancel_ClickHandler(View arg)
{
finish();
}
public void btnOk_ClickHandler(View arg)
{
txtUsername=(EditText)findViewById(com.example.androidhive.R.id.txtUserName);
txtPassword=(EditText)findViewById(com.example.androidhive.R.id.txtPassword);
if(txtUsername.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"User name can not be empty.", Toast.LENGTH_LONG).show();
return;
}
if(txtPassword.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"Password can not be empty.", Toast.LENGTH_LONG).show();
return;
}
Intent intent=new Intent();
intent.putExtra("RESULT_STRING",txtUsername.getText()+ ":"+txtPassword.getText());
setResult(RESULT_OK, intent);
finish();
}
}
Android Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidhive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".DashboardActivity" >
</activity>
<!-- Confirmation Activity -->
<activity
android:label="Confiramtion Activity"
android:name=".ConfiramtionActivity"></activity>
<!-- Login Activity -->
<activity
android:label="Login Account"
android:name=".LoginActivity"></activity>
<!-- Register Activity -->
<activity
android:label="Register New Account"
android:name=".RegisterActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android Fatal Error PLeaseeee Help:-
11-15 16:55:40.948: E/AndroidRuntime(858): FATAL EXCEPTION: main
11-15 16:55:40.948: E/AndroidRuntime(858): android.os.NetworkOnMainThreadException
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.Socket.connect(Socket.java:842)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.UserFunctions.loginUser(UserFunctions.java:32)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.LoginActivity$1.onClick(LoginActivity.java:61)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4240)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17721)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:730)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-15 16:55:40.948: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
This exception is thrown when application tries to access network in main thread. This is forbidden as accessing resources over network may take indefinite amount of time and your main thread will be blocked untill network operation finishes, thus making your app frozen to the user.
Instead in your onClick() method you should start a new AsyncTask which will do the networking. After the task finishes proceed with updating the ui (changing activity etc.).
I crate app to check the database for login info by using jsonParser.makeHttpRequest
I try to make my app to stop after 10 second in case there is no internet connection or no response from the server. The code work however when the login button click for the second time the app crash
Could anyone please support why this happen
please see the below for the code
package com.example.pfms;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String id,pass,p,logincheck;
private EditText username,password;
private Button login;
private CheckLogin cl;
private ProgressDialog pDialog;
private SharedPreferences prefs;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String url = "http://192.168.1.11/pfm/get_id.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
cl= new CheckLogin();
username=(EditText)findViewById(R.id.editText1);
password=(EditText)findViewById(R.id.editText2);
login=(Button)findViewById(R.id.button1);
prefs = this.getSharedPreferences("com.example.pfms", MODE_PRIVATE);
logincheck=prefs.getString("com.example.pfms.login", "0");
if(!logincheck.equals("0")){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",logincheck);
i.putExtras(info);
startActivity(i);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cl.execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Checking Login info. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
p="0";
pass="0";
Log.d("test", "dialog");
}
/**
* 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 {
Log.d("test", "run");
// Building Parameters
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
id=username.getText().toString();
pass=password.getText().toString();
params2.add(new BasicNameValuePair("id",id));
// getting product details by making HTTP request
// Note that product details url will use GET request
// HttpParams httpParameters = new BasicHttpParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
messageHandler.sendEmptyMessageDelayed(0, 10000);
Log.d("test", "before");
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params2);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
Log.d("test", "before success");
if (success == 1) {
// successfully received product details
JSONArray actiondetail = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject c = actiondetail.getJSONObject(0);
// Storing each json item in variable
p="";
p = c.getString("pass");
Log.d("info", "p="+p);
Log.d("info", "pass="+pass);
}else{
Toast.makeText(getBaseContext(), "Wrong Username", Toast.LENGTH_LONG).show();
}
Log.d("test", "after success");
} catch (JSONException e) {
//pDialog.dismiss();
//Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
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();
Log.d("test", "dismiss dailog");
if(p.contentEquals(pass)){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",id);
i.putExtras(info);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("com.example.pfms.login",id);
editor.commit();
startActivity(i);
}
else{
Toast.makeText(getBaseContext(), "Wrong Password", Toast.LENGTH_LONG).show();
}
}
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
cl.cancel(true);
}
};
}
please see the below for Error :
11-05 09:37:09.053: D/AndroidRuntime(1398): Shutting down VM
11-05 09:37:09.053: W/dalvikvm(1398): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 09:37:09.123: E/AndroidRuntime(1398): FATAL EXCEPTION: main
11-05 09:37:09.123: E/AndroidRuntime(1398): java.lang.IllegalStateException: Cannot execute task: the task is already running.
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.example.pfms.MainActivity$2.onClick(MainActivity.java:79)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View.performClick(View.java:4240)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View$PerformClick.run(View.java:17721)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.handleCallback(Handler.java:730)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Looper.loop(Looper.java:137)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invoke(Method.java:525)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 09:37:09.123: E/AndroidRuntime(1398): at dalvik.system.NativeStart.main(Native Method)
An object of an AsyncTask can be run only once. That is why you are getting the IllegalStateException.
Remove the object instantiation [cl= new CheckLogin()] from onCreate().
And instead,
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new CheckLogin.execute(); // creating an anonymous object of the AsyncTask makes sure that you never use it again which prevents any IllegalStateExceptions
}
});