Read data from database located at server in android - android

I have one database file whose name is menu.db and this file is located at server now i want to read data from this database.
i also have registration page on the application i am working on, as user press submit button then all the user information should be store on that database at server.
if anyone solved this problem then please help me.
if any one knows then please help me.

I have the following code. It authenticates the user password. you should call this method inside doBackground() of AsyncTask extended Class.
public boolean authenticate(String strUsername, String strPassword)
{
boolean bReturn = false;
InputStream pInputStream = null;
ArrayList<NameValuePair> pNameValuePairs = new ArrayList<NameValuePair>();
pNameValuePairs.add(new BasicNameValuePair("userid", strUsername));
pNameValuePairs.add(new BasicNameValuePair("password", strPassword));
try
{
HttpClient pHttpClient = new DefaultHttpClient();
String strURL = p_strServerIP + "Login.php";
HttpPost pHttpPost = new HttpPost(strURL);
pHttpPost.setEntity(new UrlEncodedFormEntity(pNameValuePairs));
HttpResponse pHttpResponse = pHttpClient.execute(pHttpPost);
HttpEntity pHttpEntity = pHttpResponse.getEntity();
pInputStream = pHttpEntity.getContent();
BufferedReader pBufferedReader = new BufferedReader(new InputStreamReader(pInputStream,"iso-8859-1"),8);
StringBuilder pStringBuilder = new StringBuilder();
String strLine = pBufferedReader.readLine();
pInputStream.close();
if(strLine != null)
{
if((strLine).equals("permit"))
{
bReturn = true;
}
}
}
catch (Exception e)
{
Log.e("log_tag", "Caught Exception # authenticate(String strUsername, String strPassword):" + e.toString());
}
return bReturn;
}
The class you extend from AsyncTask should be something like
class ConnectionTask extends AsyncTask<String, Void, Boolean>
{
private SharedPreferences mSettings;
private Context mContext;
ConnectionTask(SharedPreferences settings, Context context)
{
mSettings = settings;
mContext = context;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Boolean result)
{
Toast.makeText(mContext, "Authentication over.", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... params)
{
pVerifier.authenticate(params[0], params[1]);
return true;
}
}

Related

how to check if logged in previosly in android app

i am working on android application, usually when we use different app then they requires only one time user login, and when we use next time then it does not require to login again, just like Facebook ,gmail etc
i also want to have such a functionality, so that it should save the username and password in shared preference, and i am using strong loop-back API(strong loop-back is basic requirement) following code i have just written it, but i want to use Access Token for it, can have give me the idea that how to use loop-back Access Token in android...???
public boolean checkLogin() {
final SharedPreferences prefs = this.getSharedPreferences(AndroidGPSTrackingActivity.class.getSimpleName(),
this.MODE_PRIVATE);
String userName = prefs.getString("userName", "");
if (userName.isEmpty()) {
Log.i("UserName", "UserName not found.");
return false;
}
String password = prefs.getString("password", "");
if (password.isEmpty()) {
Log.i("Password", "Password not found.");
return false;
}
mCheckTask = new CheckSavedLogin(userName, password, this);
mCheckTask.execute((Void) null);
return mCheckTask.execute((Void) null);//make this return true/false
}
and also:
public class CheckSavedLogin extends AsyncTask<Void, Void, Boolean> {
public final String mUserName;
public final String mPassword;
public boolean success;
public Context context;
CheckSavedLogin(String userName, String password, Context context) {
mUserName = userName;
mPassword = password;
this.context = context.getApplicationContext();
}
protected Boolean doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://173.242.94.66/scripts/appLogin.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userName", mUserName));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(responseStr);
success = json.getBoolean("success");
Log.d("Response", responseStr);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
storeLoginDetails(mUserName, mPassword);
//RETURN TRUE HERE?
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}

Android: ProgressDialog in external async class (sth block async thread)

I have main activity:
public class ChooseWriteSentenceActivity extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String userName = "Zdzisiu";
String password = "Ziemniak";
MainServie service = new MainService(this);
boolean isExsist = service.findUser(String userName, String password);
//more code...
}
}
In my app service uses repositories and jsonconsumers but for simpler code I'm skipping them.
public class MyService{
private Context context;
public MyService(Context context){
this.context = context
}
public boolean findUser(String userName, String password){
String resultS = null;
try{
resultS = new QueryExecutorFindUser(context).execute(userName,password).get();
}
catch(Exception ex){
ex.printStackTrace();
}
boolean realRes = jsonConsumer(resultS).getFindUser();
return realRes;
}
}
public class QueryExecutorFindUser extends AsyncTask<String,Void,String> {
protected final String connectionUrl = "http://myWebService:44302/Service.svc/";
protected ProgressDialog progressDialog;
protected Context curContext;
public QueryExecutor(Context context){
curContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(curContext,"Loading...",
"Loading application View, please wait...", false, false);
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
}
protected String doInBackground(String... args){
String result = null;
String url = connectionUrl + args[0] + "/" + args[1];
HttpResponse response = null;
HttpClient httpclient = this.getNewHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
try{
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
if(response != null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
result = out.toString();
}
} else{
throw new IOException(statusLine.getReasonPhrase());
}
} catch(Exception ex){
ex.getMessage();
} finally{
if(response != null){
try{
response.getEntity().getContent().close();
} catch(Exception ex){
}
}
}
return result;
}
}
And progress dialog is show but only after all code in onCreatre in ChooseWriteSentenceActivity including doInBacground(...) from QueryExecutor is finished (so it disappears practically at the same time). It looks like sth waiting for thread with QueryExecutorFindUser.doInBackground() and it is runs like synchronously (?), I think that because when I debug code onPreExecute() is running correctly (and start before doInBackground(...)) and progressDialog.isShowing() == true (but not on the screen :( ).
If I remove extends AsyncTask from QueryExecutorFindUser and make private class with this extension in main activity (and run all code from onCreated() including service.findUser() in thisPrivateClass.doInBackground(...)) it works okey.
I prefer to have progressDialog in one place no in all main activities (of cource in practise I use QueryExecutor for all queries not only findUser) but I don't have idea what i am doing wrong. I spent all day on it with no result :(
Dialogs are tied to an Activity and ultimately must be hosted by one. So until your app's activity gets created, the dialog will not display.

android: how to save login credentials from server to phone cache

I have web services and I want to create a class that should takes an email and password from server after authentication in hash table, and then saves email and password in shared preferences.
Try this class to call webservice in your app, i am sharing get and post both methods you can use any one as per your need.
public class CallService {
String url;
HttpEntity str1;
String str;
Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public CallService(String url1) {
this.url = url1;
}
public String getResponceWithPost() {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000000);
HttpConnectionParams.setSoTimeout(httpParameters,500000);
HttpConnectionParams.setTcpNoDelay(httpParameters,true);
HttpClient hc = new DefaultHttpClient(httpParameters);
HttpPost post= new HttpPost (url);
HttpResponse rp = hc.execute(post);
// //////////////
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
str = EntityUtils.toString(rp.getEntity());
Log.e("Calling service", str);
return str;
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int getResponceWithGet() {
int code = 0;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse rp = hc.execute(get);
code= rp.getStatusLine().getStatusCode();
return code;
} catch (IOException e) {
Log.e("calling service", e.toString());
e.printStackTrace();
}
catch(Exception e)
{
Log.e("calling service", e.toString());
}
return code;
}}
this will return response from server like email password or other details.
and you can save these details in sharedpreference .
for shared preference follow this -
http://developer.android.com/guide/topics/data/data-storage.html#pref
and in your activity call your url using my call service class like this-
declare your hashTable in activity like this
Hashtable hashtable = new Hashtable();
call this method
new checkForLogin().execute();
and your async class
class checkForLogin extends AsyncTask<Void, Void,String>
{
#Override
protected void onPreExecute() {
progress= ProgressDialog.show(LoginScreen.this,"Authenticating !","Please Wait");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Parse your json data here that will be in data
CallService cl2=new CallService("your server url here");
Log.e("login url is",""+Urls.loginurl);
data=cl2.getResponceWithPost();
Log.e("server response data","data = "+data);
hashtable.put(“email″, data.getString("email"));
hashtable.put(“pass″, data.getString("pass"));
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
i hope this ll help you.

Using AsyncTask with Fragments: Android

I have used AsyncTask with Activity, And it gave me desired result without any failure.
Now I need to use AsyncTask with Fragments. In Fragments AsyncTask is not updating UI. I got an answer here. I tried that logic in my code but still I'm not able to update UI after getting response from servlet. Your help will be very appreciated.
Code what I have tried:
public class FragmentMyProfile extends Fragment
{
TextView txtViewUserFullName;
SharedPreferences shrdPref;
String currentUserFirstName = "", currentUserEmail = "";
String URL = "http://10.0.2.2:8080/iGnite_Survey/GetUserDetailsServlet";
String jsonObjectReceivedFromServer = "";
public FragmentMyProfile()
{
// empty constructor required for fragment subclass
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_my_profile, container, false);
shrdPref = rootView.getContext().getSharedPreferences("shrdPref", Context.MODE_PRIVATE);
txtViewUserFullName = (TextView) rootView.findViewById(R.id.textViewUserFullName);
//get current user first name, default value is ""
currentUserFirstName = shrdPref.getString(String.valueOf(R.string.curentLoggedInUserFirstName), "");
currentUserEmail = shrdPref.getString(String.valueOf(R.string.curentLoggedInUserEmail), "");
//display current user first name
if(!currentUserFirstName.equals(""))
{
txtViewDisplayUserFirstName.setText("Welcome "+currentUserFirstName);
}
else
{
txtViewDisplayUserFirstName.setText(String.valueOf(R.string.welcomeUser));
}
//get all user details from server
GetUserDetailsAsyncTask getUserDetailsAsyncTask = new GetUserDetailsAsyncTask (new FragmentCallback()
{
#Override
public void onTaskDone(String output)
{
//txtViewUserFullName.setText(output);
}
});
getUserDetailsAsyncTask.execute(new String[] { URL });
return rootView;
}
public interface FragmentCallback
{
public void onTaskDone(String output);
}
//------------------------------------------------------------------------------
public class GetUserDetailsAsyncTask extends AsyncTask<String, Void, String>
{
private FragmentCallback mFragmentCallback;
public GetUserDetailsAsyncTask (FragmentCallback fragmentCallback)
{
mFragmentCallback = fragmentCallback;
}
#Override
protected String doInBackground(String... urls)
{
String output = null;
for (String url : urls)
{
output = sendDataToServer(url);
}
return output;
}
#Override
protected void onPostExecute (String output)
{
super.onPostExecute(output);
mFragmentCallback.onTaskDone();
txtViewUserFullName.setText("output");
}
private String sendDataToServer(String url)
{
String output = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_email", currentUserEmail));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
output = EntityUtils.toString(httpEntity);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return output;
}
}
}
You have to use the inter-fragment communication concept to update the UI Thread from the fragment asynctask i.e INTERFACE
Please refer this tutorial with source code to understand it better : Handle Android AsyncTask Configuration Change Using Fragment

Parsing JSON from sdcard - GSON

Hi I created parsing JSON from http server based on this tutorial. But I want parse this JSON file from sdcard. I'm able to print json file location using Environment.getExternalStorageDirectory().getAbsolutePath(), But I don't know how to change the AsyncTask read the file. can someone help me to do this stuff? (I'm new to android development)
Code looks like this:
public class ClientActivity extends Activity {
TextView capitalTextView;
ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
capitalTextView = (TextView) findViewById(R.id.capital_textview);
this.retrieveCapitals();
}
void retrieveCapitals() {
progressDialog = ProgressDialog.show(this,
"Please wait...", "Retrieving data...", true, true);
CapitalsRetrieverAsyncTask task = new CapitalsRetrieverAsyncTask();
task.execute();
progressDialog.setOnCancelListener(new CancelListener(task));
}
private class CapitalsRetrieverAsyncTask extends AsyncTask<Void, Void, Void> {
Response response;
#Override
protected Void doInBackground(Void... params) {
String url = "http://sample.com/sample_data.json";
HttpGet getRequest = new HttpGet(url);
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/example.json");
System.out.println(file);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse getResponse = httpClient.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
System.out.println(this.response);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
StringBuilder builder = new StringBuilder();
for (Shop shop : this.response.shops) {
builder.append(String.format("<br>ID: <b>%s</b><br>Shop: <b>%s</b><br>Description: <b>%s</b><br><br>", shop.getId(), shop.getName(), shop.getDescription()));
}
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
}
private class CancelListener implements OnCancelListener {
AsyncTask<?, ?, ?> cancellableTask;
public CancelListener(AsyncTask<?, ?, ?> task) {
cancellableTask = task;
}
#Override
public void onCancel(DialogInterface dialog) {
cancellableTask.cancel(true);
}
}
}
Don't save the JSON file as it is. JSON is meant for transferring values from one place to another.
Instead, depending on the data, you can use Shared Preference or SQLite database to store it.
Check this out:
http://developer.android.com/guide/topics/data/data-storage.html
Then you can easily retrieve it and make modifications to the data.

Categories

Resources