This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am in the process of developing a registration app using Android Studios, however once users try to register the application just says error in registration and the LogCat does not give any error, as well as when debugging the app, I still get no errors.
Please can you help and tell me where I am going wrong as the code is correct as it was working couple of months ago, however since I have returned from holiday it just says "Error occurred in registration".
User data gets entered into the database however it does not allow the user to move onto the next activity as it says "Error occurred in registration". Please can you help or advise?
LogCat
01-07 15:14:42.933 2161-4203/com.Oakland E/JSON Parser: Error parsing data org.json.JSONException: Value 2016-01-07 of type java.lang.String cannot be converted to JSONObject
01-07 15:14:42.938 2161-2161/com.Oakland E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.Oakland, PID: 2161
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
at com.Oakland.Register$ProcessRegister.onPostExecute(Register.java:211)
at com.Oakland.Register$ProcessRegister.onPostExecute(Register.java:171)
Line 211- if (json.getString(KEY_SUCCESS) != null) {
Register.Java
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
ImageButton btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
NetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occurred in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
UserFunction.Java
//URL of the PHP API
private static String registerURL = "http://10.0.2.2/Register_api/";
private static String register_tag = "register";
/**
* Function to Register
**/
public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("fname", fname));
params.add(new BasicNameValuePair("lname", lname));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
return json;
}
JsonPasar.Java
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
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
DatabaseHandler.Java
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "cloud_contacts";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FIRSTNAME = "fname";
private static final String KEY_LASTNAME = "lname";
private static final String KEY_EMAIL = "email";
private static final String KEY_USERNAME = "uname";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_FIRSTNAME + " TEXT,"
+ KEY_LASTNAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_USERNAME + " TEXT,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String fname, String lname, String email, String uname, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, fname); // FirstName
values.put(KEY_LASTNAME, lname); // LastName
values.put(KEY_EMAIL, email); // Email
values.put(KEY_USERNAME, uname); // UserName
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("fname", cursor.getString(1));
user.put("lname", cursor.getString(2));
user.put("email", cursor.getString(3));
user.put("uname", cursor.getString(4));
user.put("uid", cursor.getString(5));
user.put("created_at", cursor.getString(6));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
You should edit your log statement or add a log statement to show what the string you're trying to convert to a json object contains. I also think it would be appropriate to instantiate the JSONObject on the spot rather than having a static variable.
Log.e("Buffer Error", "Error converting result " + json);
JSONObject jObj = new JSONObject(json);
To prevent the null pointer you should change your if statement to:
if(json != null && json.getString(KEY_SUCCESS) != null)
What's happening is there is a problem with your JSONObject creation and it's trying to call getString on the resultantly null JSONObject.
Related
I created application to pass data from android device to web API.
1.As a first step user should login and if he is valid user application save the token value.
2.Then go to add product interface. In that interface user can add new products to the server.
3.To do this task user should pass token value to the header field at the API.
4.Other details into body field at the API.
This is my login activity
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterInfo.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
*/
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//String token = jObj.getString("token");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
} else {
//Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
//e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
// Launch main activity
String token=e.getMessage();
new Sharedpreference(token);
Intent intent = new Intent(LoginActivity.this,
Product_Dashboard.class);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
This is my product activity
public class MainActivity extends Activity {
private EditText productName;
private EditText Category;
private EditText Description;
private EditText UnitPrice;
private EditText from;
private EditText to;
private EditText Quty;
RadioGroup priceoption;
RadioGroup Quantityoption;
Button Addproductbtn;
public static final String PREFS_NAME = "AOP_PREFS";
public final String PREFS_KEY = "AOP_PREFS_String";
private String Aceept = "#'application/vnd.fxhello.v1+json'";
private String token1;
private String Authontication = "Bearer$" +token1;
//--READ data
// String token = preferences.getString("var1", 0);
String price1 = "TRUE";
String qtySelect1 = "TRUE";
private String service1 = "";
private String limitedQty1 = "";
private String lqty1 = "";
public String getValue(Context context) {
SharedPreferences settings;
String text;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
text = settings.getString(PREFS_KEY, null); //2
token1=text;
return text;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productName = (EditText) findViewById(R.id.productnameeditText);
Category = (EditText) findViewById(R.id.CategoryeditText);
Description = (EditText) findViewById(R.id.DescriptioneditText);
UnitPrice = (EditText) findViewById(R.id.UnitPriceeditText);
from = (EditText) findViewById(R.id.FromeditText);
to = (EditText) findViewById(R.id.ToeditText);
Quty = (EditText) findViewById(R.id.EnterquantityeditText);
priceoption = (RadioGroup) findViewById(R.id.priceoption);
Quantityoption = (RadioGroup) findViewById(R.id.Quantityoption);
Addproductbtn =(Button)findViewById(R.id.AddNewProductbtn);
Addproductbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String price = price1.toString();
String unit_price = UnitPrice.getText().toString();
String up = unit_price.toString();
String price_range_from = from.getText().toString();
String prf = price_range_from.toString();
String price_range_to = to.getText().toString();
String prt = price_range_to.toString();
String product_name = productName.getText().toString();
String pn = product_name.toString();
String category = Category.getText().toString();
String ct = category.toString();
String description = Description.getText().toString();
String des = description.toString();
String qtySelect = qtySelect1.toString();
String qty = Quty.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lmtq = limitedQty.toString();
String lqty = lqty1.toString();
insertToDatabase(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
Toast.makeText(getApplicationContext(), "New Product Added!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void insertToDatabase(String price, String up, String prf, String prt, String pn, String ct, String des, String qty, String service, String lmtq, String lqty) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paraprice = params[0];
String paraunit_price = params[1];
String paraprice_range_from = params[2];
String paraprice_range_to = params[3];
String paraproduct_name = params[4];
String paracategory = params[5];
String paraDescription = params[6];
String paraqtySelect = params[7];
String paraqty = params[8];
String paraservice = params[10];
String paralimitedQty = params[11];
String paralqty = params[12];
String price = price1.toString();
String Up = up.toString();
String Prf = prf.toString();
String Prt = prt.toString();
String Pn = pn.toString();
String Ct = ct.toString();
String Des = des.toString();
String qtySelect = qtySelect1.toString();
String Lmtq = lmtq.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lqty = lqty1.toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("price", price));
nameValuePairs.add(new BasicNameValuePair("unit_price", Up));
nameValuePairs.add(new BasicNameValuePair("price_range_from", Prf));
nameValuePairs.add(new BasicNameValuePair("price_range_to", Prt));
nameValuePairs.add(new BasicNameValuePair("product_name", Pn));
nameValuePairs.add(new BasicNameValuePair("category", Ct));
nameValuePairs.add(new BasicNameValuePair("description", Des));
nameValuePairs.add(new BasicNameValuePair("qtySelect", qtySelect));
nameValuePairs.add(new BasicNameValuePair("lmtq", lmtq));
nameValuePairs.add(new BasicNameValuePair("service", service));
nameValuePairs.add(new BasicNameValuePair("limitedQty", limitedQty));
nameValuePairs.add(new BasicNameValuePair("lqty", lqty));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://uat.fxhello.com/api/seller/productCreate");
httpPost.setHeader("Accept", Aceept);
httpPost.setHeader("Authorization",Authontication);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
}
}
I got this error
FATAL EXCEPTION: AsyncTask #3
Process: com.example.official2.xoxo, PID: 2364
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=11; index=11
at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:143)
at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:131)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
12-15 10:09:11.859 2364-2379/com.example.official2.xoxo E/EGL_emulation: tid 2379: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)
in local when i click on button "LOGIN" i have this exception?
> W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Here is my code;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DBConnect.php:
class DB_Connect {
private $conn;
// Connecting to database
public function connect() {
require_once 'include/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
DBFunction.php:
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
/**
* Encrypting password
* #param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* #param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
REGISTER ACTIVITY.java:
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
LOGIN ACTIVITY.java:
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And here is AppConfig.java
public class AppConfig {
// Server user login url
// public static String URL_LOGIN = "http://192.168.0.102/android_login_api/login.php";
//public static String URL_LOGIN = "http://10.0.2.2:8888/android_login_api/login.php";
public static String URL_LOGIN = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/login.php";
// Server user register url
//public static String URL_REGISTER = "http://10.0.2.2:8888/android_login_api/register.php";
public static String URL_REGISTER = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/register.php";
}
register.php:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (name, email or password) is missing!";
echo json_encode($response);
}
LOGIN.php:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
LOGCAT:
07-13 19:55:24.137 11917-11917/ W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSONObject.<init>(JSONObject.java:158)
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSONObject.<init>(JSONObject.java:171)
07-13 19:55:24.137 11917-11917/ W/System.err: at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:127)
07-13 19:55:24.137 11917-11917/ W/System.err: at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:119)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Handler.handleCallback(Handler.java:605)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Looper.loop(Looper.java:137)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.app.ActivityThread.main(ActivityThread.java:4424)
07-13 19:55:24.137 11917-11917/W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 19:55:24.137 11917-11917/ W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-13 19:55:24.137 11917-11917/ W/System.err: at dalvik.system.NativeStart.main(Native Method)
json_encode() your output then try to parse it. It will solve your issue.
I had faced same situation and i created module for it.I am attaching a sample code how to retrive json object from php to android .
your php code must be :-
<?php
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$class_id="2";
function getClassById($class_id) {
$ss="SELECT * FROM student WHERE class_id = '$class_id'";
$result = mysql_query($ss) or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
}
else {
// user not found
return false;
}
}
$user =getClassById($class_id);
if ($user != false) {
$response["success"] = 1;
$response["user"]["class_id"] = $user["class_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["enrolment"] = $user["enrolment"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
?>
Now your code can be anything which you want but it must have json_encode() for getting json object in android.
Now your android coding must be like .
public class UserFunctions {
private JSONParser jsonParser;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static final String TAG_SECTION ="sectionof";
private static final String TAG_ClassKey ="classkey";
private static final String TAG_cordinator ="coordinatoremail";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
//URL of the PHP API
private static String GetbunkstudentURL = "http://169.254.90.189/learn2crack_login_api/getabsentstudent/getabsentstudent.php";
private static String bunk_tag = "bunk";
private static String register_tag = "register"; // constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
public JSONObject getBunkStudent(String lecture1, String lecture2) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", bunk_tag));
params.add(new BasicNameValuePair("lec1", lecture1));
params.add(new BasicNameValuePair("lec2", lecture2));
JSONObject json = jsonParser.getJSONFromUrl(GetbunkstudentURL, params);
return json;
}
}
Now your jsonparser.java class must be like:-
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
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
code to call those function in activity or in fragment is here,
public class seeBunkedStudentFragment extends ListFragment {
String myJSON;
private static final String KEY_STUDENT="student";
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_ClassDet = "classdetails";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_SECTION ="sectionof";
//////tags
private static final String TAG_TID = "tid";
private static final String Tag_Classid="classid";
private static final String Tag_Classkey="classkey";
private static final String Tag_schedid="scheduleid";
////////
JSONArray peoples = null;
JSONArray contacts = null;
ArrayList<HashMap<String, String>> contactList;
public ArrayList<HashMap<String, String>> personList;
ListView list;
private HashMap<String, String> singleclass;
String userdetail[]=new String[5];
private String todayda;
private String result;
private String ccid,ssid;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.bunkstudentlist,null);
list = (ListView) v.findViewById(R.id.list);
NetAsync(v);
contactList = new ArrayList<HashMap<String, String>>();
personList = new ArrayList<HashMap<String,String>>();
return v;
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(getActivity());
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
/*
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
// return false;
return true;
}
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "Error in Network Connection", Toast.LENGTH_LONG).show();
}
}
}
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String uniq;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
String lecture1="1";
String lecture2="2";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getBunkStudent(lecture1,lecture2);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = null;
try {
res = json.getString(KEY_SUCCESS);
} catch (JSONException e1) {
e1.printStackTrace();
}
res= json.getString("success");
JSONArray json_user = json.getJSONArray("user");
int llenggt=json_user.length();
if(Integer.parseInt(res) == 1){
for (int i = 0; i < json_user.length(); i++) {
JSONObject c = json_user.getJSONObject(i);
String tid = c.getString("teacherid");
String classid= c.getString("enrollmentnumber");
String classkey= c.getString("classid");
Log.d("firstjson",tid+""+classid+""+classkey);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
//TAG_TID, Tag_Classid, Tag_Classkey // adding each child node to HashMap key => value
contact.put(TAG_TID, tid);
contact.put(Tag_Classid, classid);
contact.put(Tag_Classkey, classkey);
// adding contact to contact list
contactList.add(contact);
}
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
////
myJSON=result;
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.item_fetch_lec2, new String[]{TAG_TID, Tag_Classid,
Tag_Classkey}, new int[]{R.id.name,
R.id.email, R.id.mobile});
setListAdapter(adapter);
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
//////code for othere async task
}
i think it will help , you just take reference from these code it will help .
Add this code before the line of your JSONObject,
Log.i("tagconvertstr", "["+response+"]");
Then you can know what's your error.
And don't forget to call your AppController class in Manifest.xml
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hi i'm completely new to Android. Very used to .Net and SQL Server. Hence, having issue adopting to SQLite. I'm currently able to display the result in a listView from a URL via HttpGet. Kindly be gentle with me. Helps are greatly appreciated, as I'm stuck in SQLite for the past week.
Just want check if it's possible to set it such that
HttpGet will retrieve and insert into SQLite table.
listView retrieve All columns data from SQLite table.
The HttpGet AsyncTask will run only if 48hrs has pass. So for example if the the download happens on Monday, the database should not be updated if the person use the app on Tuesday. However, the data will be updated on Wed when the user on it.
It will delete all column in the table before inserting into SQlite table.
EncounterActivity.Java
public class EncounterActivity extends Activity {
ListView list;
TextView eid;
TextView eclerkship;
TextView ename;
TextView etype;
TextView erequiredattempts;
EncounterDbAdapter encounterDB;
Context myContext;
Button Btngetdata;
ArrayList<HashMap<String, String>> encouterlist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "SorryHadToRemoveThisDueToSomeReason";
//JSON Node Names
private static final String TAG_ENCOUNTERS = "encounters";
private static final String TAG_E_ID = "e_id";
private static final String TAG_E_CLERKSHIP = "clerkship";
private static final String TAG_E_NAME = "encounter_name";
private static final String TAG_E_TYPE = "type";
private static final String TAG_E_REQUIRED_ATTEMPTS = "required_attempts";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encounter);
encouterlist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
eid = (TextView)findViewById(R.id.eid);
eclerkship = (TextView)findViewById(R.id.eclerkship);
ename = (TextView)findViewById(R.id.ename);
etype = (TextView)findViewById(R.id.etype);
erequiredattempts = (TextView)findViewById(R.id.erequiredattempts);
pDialog = new ProgressDialog(EncounterActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_ENCOUNTERS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String eid = c.getString(TAG_E_ID);
String eclerkship = c.getString(TAG_E_CLERKSHIP);
String ename = c.getString(TAG_E_NAME);
String etype = c.getString(TAG_E_TYPE);
String erequiredattempts = c.getString(TAG_E_REQUIRED_ATTEMPTS);
// Opening of database
encounterDB = new EncounterDbAdapter(myContext);
encounterDB.open();
encounterDB.insertEncounterEntry(eid, eclerkship, ename, etype, erequiredattempts);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_E_ID, eid);
map.put(TAG_E_CLERKSHIP, eclerkship);
map.put(TAG_E_NAME, ename);
map.put(TAG_E_TYPE, etype);
map.put(TAG_E_REQUIRED_ATTEMPTS, erequiredattempts);
encouterlist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(EncounterActivity.this, encouterlist,
R.layout.list_v,
new String[] { TAG_E_ID, TAG_E_CLERKSHIP, TAG_E_NAME, TAG_E_TYPE, TAG_E_REQUIRED_ATTEMPTS }, new int[] {
R.id.eid, R.id.eclerkship, R.id.ename, R.id.etype, R.id.erequiredattempts});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(EncounterActivity.this, "You Clicked at "+encouterlist.get(+position).get("type"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
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;
}
}
EncounterDbAdapter.java
public class EncounterDbAdapter {
private static final String DATABASE_NAME = "mediLearner.db";
private static final String DATABASE_TABLE = "EncounterDb";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase _db;
private final Context context;
public static final String E_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String CLERKSHIP = "entry_clerkship";
public static final int COLUMN_CLERKSHIP_ID = 1;
public static final String ENCOUNTER_NAME = "entry_encounter";
public static final int COLUMN_ENCOUNTER_NAME = 2;
public static final String TYPE = "entry_type";
public static final int COLUMN_TYPE = 3;
public static final String REQUIRED_ATTEMPTS = "entry_requiredAttempts";
public static final int COLUMN_REQUIRED_ATTEMPTS = 4;
protected static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + E_ID
+ " PRIMARY KEY, " + CLERKSHIP + " Text, "
+ ENCOUNTER_NAME + " text, " + TYPE + " Text, "
+ REQUIRED_ATTEMPTS + " Text);";
private String encounterDBADAPTER_LOG_CAT = "MY_LOG";
private myDBOpenHelper dbHelper;
public EncounterDbAdapter(Context _context) {
this.context = _context;
dbHelper = new myDBOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public void close() {
_db.close();
Log.w(encounterDBADAPTER_LOG_CAT, "DB closed");
}
public void open() throws SQLiteException {
try{
_db=dbHelper.getWritableDatabase();
Log.w(encounterDBADAPTER_LOG_CAT, "DB opened as writable database");
}catch(SQLiteException ex){
_db=dbHelper.getReadableDatabase();
Log.w(encounterDBADAPTER_LOG_CAT, "DB opened as readable database");
}
}
//insertion
public long insertEncounterEntry(String ID , String clerkship, String encounter, String type, String requiredAttempts ) {
//insert new task
ContentValues newEntryValues=new ContentValues();
newEntryValues.put(E_ID, ID);
newEntryValues.put(CLERKSHIP,clerkship);
newEntryValues.put(ENCOUNTER_NAME,encounter);
newEntryValues.put(TYPE, type);
newEntryValues.put(REQUIRED_ATTEMPTS, requiredAttempts);
//Insert the row
Log.w(encounterDBADAPTER_LOG_CAT, "Inserted E_ID="+ID+" CLERKSHIP="+clerkship + "Inserted ENCOUNTER_NAME="+encounter + "Inserted TYPE="+type + "Inserted REQUIRED_ATTEMPTS="+requiredAttempts +"into table"+DATABASE_TABLE);
return _db.insert(DATABASE_TABLE, null, newEntryValues);
}
public boolean removeEntry(long _rowIndex) {
if(_db.delete(DATABASE_TABLE, E_ID+"="+_rowIndex, null)<=0)
{
Log.w(encounterDBADAPTER_LOG_CAT,"Removing Entrying where id="+_rowIndex+"Failed");
return false;
}
Log.w(encounterDBADAPTER_LOG_CAT,"Removing Entrying where id="+_rowIndex+"Success");
return true;
}
//updating
public boolean updateEntry(int ID , String clerkship, String encounter_name, String type, String requiredAttempts ) {
return false;
}
//retrival
public Cursor retrieveAllEntriesCursor() {
Cursor c=null;
try{
c=_db.query(DATABASE_TABLE,new String[]{E_ID, CLERKSHIP, ENCOUNTER_NAME, TYPE, REQUIRED_ATTEMPTS}, null,null,null,null,null);
}catch(SQLException sle){
Log.w(encounterDBADAPTER_LOG_CAT,"Retrieve fail!!");
}
return c;
}
public class myDBOpenHelper extends SQLiteOpenHelper {
public myDBOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
Log.w(encounterDBADAPTER_LOG_CAT, "Helper : DB " + DATABASE_TABLE
+ " Created!!");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
} // End of myDBOpenHelper
}// End of myDBAdapter
I would not use a Timer for the updates, but instead use a Service that starts on an interval set up by the AlarmManager. Like this:
public void setScheduling() {
Date now = new Date();
// Set the time to download to 18:00
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartDownloadReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.cancel(pi);
// 1 * 24 * 60 * 60 * 1000 = repeat this every day
mgr.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 1 * 24 * 60 * 60 * 1000, pi);
}
Handle the pending intent in a BroadcastReceiver:
public class StartDownloadReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean autoDownload = sharedPreferences.getBoolean("auto_download", false);
if (autoDownload) {
context.startService(new Intent(context, DownloaderService.class));
}
}
}
In your download service you would then use an AsyncTask to do the downloading, parsing and updating of the database.
I recently finished an app with somewhat the exact same requirements;
every day at 18:00 download an RSS feed
If the download and parsing was successful wipe the database tables and update the data
Send a broadcast to let any Activity that might be open to refresh its ListView
That's basically it, though the implementation is not exactly like that.
Have a look at it here: https://github.com/slidese/SGU
Also: I'm using OrmLite when working with SQLite. I find it to be far easier and quicker to work with than dealing with the SQL directly.
I want to store an json data to db,it has to display my apps has to display some previous data without internet time also.For that i want to create an db for json data to store.
This is the db part i created for json data.
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "ginfy.db";
private static final String DATABASE_TABLE_PROJ = "prayers";
private static final int DATABASE_VERSION = 2;
public static final String CATEGORY_COLUMN_ID = "id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "ProjectDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public GinfyDbAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
public GinfyDbAdapter GinfyDbAdapter(Context context){
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key autoincrement, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer primary key autoincrement );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER PRIMARY KEY )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
}
this is mainactivity which is showing listview
public class MainActivity extends Activity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final String TAG_CATEGORY = "post";
private static final String CATEGORY_COLUMN_ID = "id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
//JSONParser jParser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(id,title,content,count);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(CATEGORY_COLUMN_ID, id);
map.put(CATEGORY_COLUMN_TITLE, title);
map.put(CATEGORY_COLUMN_CONTENT, content);
map.put(CATEGORY_COLUMN_COUNT, count);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data){
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
/*dataAdapter adapter = new SimpleCursorAdapter(this,
R.layout.activity_row,
new String[] { CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, new int[] {
R.id.text2, R.id.text1, R.id.count });*/
//lv.setListAdapter(adapter);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg){
if ( dialog != null )
dialog.dismiss();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
Before using db it shows in listview also,rite now i want to make db also,for that i wrote some code in mainactivity.
Fetchdatatask.java
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private OnClickListener onClickListener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
app.setTitle(json.getString("title"));
app.setCount(Integer.parseInt(json.getString("count")));
app.setId(Integer.parseInt(json.getString("id")));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
This fetchdatatask fetch from json and showing in listview,i want that without internet time it has to show in listview also for that i am creating db.
can you check my code is correct,actually it showing error in mainactivity line JSONArray aJson = jsonObject.getJSONFromUrl(url);
Create a class which act's as the intermediate between your Db class and the main activity to insert the data into the db and vice versa
public class Category {
String id;
String title;
String content;
String count;
public Category(String id, String title, String content, String count) {
super();
this.id = id;
this.title = title;
this.content = content;
this.count = count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
In your main activity where you do the json parsing create an object of DB class and call one the save record method at there like i did below
DatabaseHelper mDbHelper;
public class ABC extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
mDbHelper= new DatabaseHelper (this);
new GetSyncDataAsyncTask().execute();
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(ABC.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Dialog.dismiss();
Intent intent = new Intent(ABC.this, XYZ.class);
startActivity(intent);
}
#Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
}
public void getProdData() {
// getting JSON string from URL
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
At last in your db class insert the values like below
public void saveCategoryRecord(Category category) {
String query = "insert into"+ TABLE_NAME+ values( ?, ?, ?, ?, ?, ? )";
SQLiteStatement stmt = mDb.compileStatement(query);
stmt.bindString(1, category.getId());
stmt.bindString(2, category.getTitle());
stmt.bindString(3, category.getContent());
stmt.bindString(4, category.getCount());
stmt.execute();
}
I have tried to use the same things as you have used. This is the way i think now you got the concept to do that
i am working in an application, i seen that guide: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ and i make it working on mine app...
Now the login part is this:
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView testo;
// 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);
testo = (TextView) findViewById(R.id.testo);
// 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 json parser is:
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
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and the database handler:
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
now i want to put in a textview the username of the user logged in, but i have no idea on how to do it... i have to use the parser? i have to read the sqlite database? can someone help me? thanks, i'm newbie in that thing...
you can do this by passing the user name to the DashboardActivity. You have to add the following line just before the line startActivity(dashboard); in your LoginActivity class.
dashboard.putExtra("username", json_user.getString(KEY_NAME));
This line passes the username to your DashboardActivity.
Then, in the method onCreate of your DashboardActivity we will get the user name and put it on a variable called username (a String) with the code:
Intent intent = getIntent();
String username = "";
if(intent != null) {
username = intent.getStringExtra(name);
}