dimanche 25 janvier 2015

How to extract data from sqlite database

In my app the process of authenticate login is done by web api service. When after authentication what i am trying is to store user data of json return from web service in local sqlite database, and after then login to home page then i want to pull out and test whether the data has stored or not by clicking button and to display user data in toast.


json return after succesful login



{
error: false
name: "name"
email: "name111@gmail.com"
apiKey: "8b2adfdsfjhkdfhkadshjfsdfh"
}


This is my login activity page



public class LoginActivity extends Activity {

private static final String SERVICE_URL = "http://ift.tt/1CSTw7M;
private static final String TAG = "LoginActivity";
Context ctx= this;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
public void loginUser(View vw) {
EditText Name1 = (EditText) findViewById(R.id.loginEmail);
EditText Name2 = (EditText) findViewById(R.id.loginPassword);
String email = Name1.getText().toString();
String password = Name2.getText().toString();
if(Utility.isNotNull(email) && Utility.isNotNull(password) ){
// When Email entered is Valid
if(Utility.validate(email)){
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Posting data...");
wst.addNameValuePair("email", email);
wst.addNameValuePair("password", password);
wst.execute(new String[]{SERVICE_URL});
}
// When Email is invalid
else{
Toast.makeText(getApplicationContext(), "Please enter valid email", Toast.LENGTH_LONG).show();
}

}
// When any of the Edit View control left blank
else{
Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show();
}
}

public void handleResponse(String response) {

try {

JSONObject jso = new JSONObject(response);
if(jso.getBoolean("error")){

Toast.makeText(getApplicationContext(), jso.getString("message"), Toast.LENGTH_LONG).show();

}
// Else display error message
else{

String name2 = jso.getString("name");
String name3 = jso.getString("email");
String name4 = jso.getString("apiKey");
Toast.makeText(this, "Name: "+name2+"\n Email:"+name3+"\n ApiKey: "+name4, Toast.LENGTH_LONG).show();
todatabse(name2, name3, name4);
homeScreen(name2);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
//Inserting to sqlite database
public void todatabse(String name1, String name2, String name3)
{
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, name1, name2, name3);
Toast.makeText(getApplicationContext(), "inserted to sqlite", Toast.LENGTH_LONG).show();
finish();
}

private class WebServiceTask extends AsyncTask<String, Integer, String> {

public static final int POST_TASK = 1;
public static final int GET_TASK = 2;

private static final String TAG = "WebServiceTask";

// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;

// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;

private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";

private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

private ProgressDialog pDlg = null;

public WebServiceTask(int taskType, Context mContext, String processMessage) {

this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}

public void addNameValuePair(String name, String value) {

params.add(new BasicNameValuePair(name, value));
}

private void showProgressDialog() {

pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();

}

@Override
protected void onPreExecute() {

hideKeyboard();
showProgressDialog();

}

protected String doInBackground(String... urls) {

String url = urls[0];
String result = "";

HttpResponse response = doResponse(url);

if (response == null) {
return result;
} else {

try {

result = inputStreamToString(response.getEntity().getContent());

} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);

} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}

}

return result;
}

@Override
protected void onPostExecute(String response) {

handleResponse(response);
pDlg.dismiss();

}

// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {

HttpParams htpp = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

return htpp;
}

private HttpResponse doResponse(String url) {

// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());

HttpResponse response = null;

try {
switch (taskType) {

case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));

response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {

Log.e(TAG, e.getLocalizedMessage(), e);

}

return response;
}

private String inputStreamToString(InputStream is) {

String line = "";
StringBuilder total = new StringBuilder();

// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));

try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}

// Return full string
return total.toString();
}

}

public void homeScreen(String s2){
Intent homeIntent = new Intent(getApplicationContext(),HomeActivity.class);
Bundle extras = new Bundle();
extras.putString("EXTRA1",s2);
homeIntent.putExtras(extras);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}


}


After login to homepage i make one button for to switch to other page again for test extracting datas. This is the page what i am trying to test for pulling datas



public class About extends Activity {

Context CTX;//when i put "CTX = this", In logcat it shows activity of recreating database
//without it show this errors
/*java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.about);
getActionBar().hide();

}
//this function is name of onClick of Button
public void dbfunction(View vw)
{
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
String Name="", Email= "", Apikey="";
CR.moveToFirst();
do{
Name= CR.getString(0);
Email=CR.getString(1);
Apikey=CR.getString(2);

}while(CR.moveToNext());
//extracting from database
Toast.makeText(getApplicationContext(),"Name="+Name+"\n Email="+Email+"\n Apikey"+Apikey,Toast.LENGTH_LONG);

}


}


database helper class


public class DatabaseOperations extends SQLiteOpenHelper {



public static final int database_version =1;
public String CREATE_QUERY = "CREATE TABLE "+ TableData.TableInfo.TABLE_NAME+" ("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_EMAIL+" TEXT,"+ TableData.TableInfo.USER_APIKEY+" TEXT);";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, database_version);
Log.d("Database operations", "Datbase created");
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.d("Database operations", "Table created");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void putInformation(DatabaseOperations dop, String name, String email, String apikey)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();

cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_EMAIL, email);
cv.put(TableData.TableInfo.USER_APIKEY, apikey);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Database operations", "One row inserted");
}

public Cursor getInformation(DatabaseOperations dop)
{
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_NAME, TableData.TableInfo.USER_EMAIL, TableData.TableInfo.USER_APIKEY};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}


}


It can insert data after login to home but Why it can not extract data from other activity layout.


Aucun commentaire:

Enregistrer un commentaire