how to use content provider to access shared preferences - java

i have a registration app in the making where the user registers the data and on the other end the data can be shown and viewed and manipulated , i am using shared preferences method as shown below to write and access data (you can see them in DataEntry.java & DataManipulation.java shown below) but i want to use content provider method to manipulate data like quering or inserting or deleting....is there a way to do this and if yes can you please tell me how?
thank you
here are the codes below
the User end DataEntry.java:
package com.hossa.datamanipulation;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DataEntry extends Activity {
/*
* here is the part the user will submit several data for several people
*/
Button Submit, BroadcastButton;
TextView User, Email, Mobile;
EditText UserEdit, EmailEdit, MobileEdit;
String UserValue, EmailValue, MobileValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dataentry);
Submit = (Button) findViewById(R.id.DataSubmit);
BroadcastButton = (Button) findViewById(R.id.Broadcast);
User = (TextView) findViewById(R.id.TVuser);
Email = (TextView) findViewById(R.id.TVemail);
Mobile = (TextView) findViewById(R.id.TVmobile);
UserEdit = (EditText) findViewById(R.id.Edituser);
EmailEdit = (EditText) findViewById(R.id.Editemail);
MobileEdit = (EditText) findViewById(R.id.Editmobile);
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// saving the data of the user//
SharedPreferences sp = getSharedPreferences("userdata",
MODE_PRIVATE);// name of the file and it's mode//
SharedPreferences.Editor edit = sp.edit();// to be able to edit
// the file//
edit.putString("Username", UserEdit.getText().toString());// get
// the
// input
// username//
edit.putString("Email", EmailEdit.getText().toString());// get
// the
// input
// Email//
edit.putString("Mobile", MobileEdit.getText().toString());// get
// the
// input
// Mobile//
edit.commit();
Toast.makeText(getApplicationContext(),
"Data is Saved Successfully", Toast.LENGTH_SHORT)
.show();
}
});
BroadcastButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent e = new Intent();
e.setAction("com.hossa.data" + "manipulation.custombroadcast");
sendBroadcast(e);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and the other end DataManipulaton.java:
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DataManipulation extends Activity {
Button ImportButton, ViewButton, RetrieveButton;
EditText UserShow;
TextView EmailDisplay, UserDisplay, MobileDisplay, EmailTV, UserTV,
MobileTV;
public static final String defaultvalue = "N/A";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datamanipulation);
ContentResolver ct = getContentResolver();
String Path = "data/data/com.hossa.datamanipulation/files/userdata";
Uri uri = Uri.parse("content://" + Path);
ImportButton = (Button) findViewById(R.id.ImportButton);
ViewButton = (Button) findViewById(R.id.ViewButton);
RetrieveButton = (Button) findViewById(R.id.RetrieveButton);
EmailDisplay = (TextView) findViewById(R.id.EmailDisplay);
MobileDisplay = (TextView) findViewById(R.id.MobileDisplay);
UserDisplay = (TextView) findViewById(R.id.UsernameDisplay);
EmailTV = (TextView) findViewById(R.id.EmailTV2);
UserTV = (TextView) findViewById(R.id.UserTV2);
MobileTV = (TextView) findViewById(R.id.MobileTV2);
final String U1[] = new String[10];
final String E1[] = new String[10];
final String M1[] = new String[10];
final String[][] alldata = new String[][] { U1, M1, E1 };
RetrieveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int i = 0;
SharedPreferences spdata = getSharedPreferences("userdata",
Context.MODE_PRIVATE);
while (spdata.getString("Username", defaultvalue) != null) {
String tempuser = spdata
.getString("Username", defaultvalue);
U1[i] = tempuser;
i++;
}
i = 0;
while (spdata.getString("Email", defaultvalue) != null) {
String tempemail = spdata.getString("Email", defaultvalue);
E1[i] = tempemail;
i++;
}
i = 0;
while (spdata.getString("Mobile", defaultvalue) != null) {
String tempmobile = spdata
.getString("Mobile", defaultvalue);
M1[i] = tempmobile;
i++;
}
i = 0;
}
});
ImportButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getApplicationContext();
// TODO Auto-generated method stub
SharedPreferences sp = getSharedPreferences("userdata",
Context.MODE_PRIVATE);
String Username = sp.getString("Username", defaultvalue);
String Email = sp.getString("Email", defaultvalue);
String Mobile = sp.getString("Mobile", defaultvalue);
// what if there is no data from the user??//
if (Username.equals(defaultvalue) || Email.equals(defaultvalue)
|| Mobile.equals(defaultvalue)) {
Toast.makeText(getApplicationContext(),
"no data has been entered", Toast.LENGTH_SHORT)
.show();
} else {
UserTV.setText(Username);
EmailTV.setText(Email);
MobileTV.setText(Mobile);
}
}
});
//THE BELOW IS THE SECTION I NEED HELP WITH...THE ABOVE IS SIMPLY SOME TRIALS AND TESTS//
Cursor c = ct.query(uri, U1, null, null, null);
// c=ct.delete(uri, where, selectionArgs);
// c=ct.update(uri, values, where, selectionArgs);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PLEASE NOTE THAT BOTH CLASSES ARE IN THE SAME PACKAGE SO IT IS THE SAME APP NOT 2 DIFFERENT APPS

Related

How to display all data from sqlite database

I'm making an app that will let users add their school subjects.
Before i continue let me give you my code:
MainActivity:
package cannon.gaming.mymarks;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
TextView textSubject;
String SUBJECT, PASS;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
textSubject = (TextView) findViewById(R.id.textSubject);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TableData:
package cannon.gaming.mymarks;
import android.provider.BaseColumns;
/**
* Created by Asuspc on 01/07/2015.
*/
public class TableData {
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String USER_NAME = "user_name";
public static final String USER_PASS = "user_pass";
public static final String DATABASE_NAME = "user_info";
public static final String TABLE_NAME = "reg_info";
}
}
DatabaseOperations:
package cannon.gaming.mymarks;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Asuspc on 01/07/2015.
*/
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_PASS+" TEXT);";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, database_version);
Log.d("Database Operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb)
{
sdb.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
{
}
public void putInformation(DatabaseOperations dop,String name, String pass)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
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[] columns = {TableData.TableInfo.USER_NAME, TableData.TableInfo.USER_PASS};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
return CR;
}
}
Now let me explain.
When I press the "buttonAdd" button it will let me enter the subject name obviously, and save it in database.
But what I can't make is, I want to display all database on MainActivity.
And it should be like this:
names of subjects on the left side,
average of those subjects on the right side (the string PASS should be that average, that's why it is 0 when you first add the subject).
And I want to make each of those subjects clickable, so when you click it it should show you all marks from that subject and let you add or remove them.
Now, I guess, displaying data shouldn't be so hard, but still I need your help.
But making each subject clickable I really have no idea how.
And each subject having its own marks, I don't know, does it mean new activity for every new subject or new database or what?
EDIT:
MainActivity now:
package cannon.gaming.mymarks;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
String SUBJECT, PASS;
Context CTX = this;
private SimpleCursorAdapter adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
displayListView();
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(CTX);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
displayListView();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayListView()
{
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
// The desired columns to be bound
String[] columns = new String[]{
TableData.TableInfo.USER_NAME,
TableData.TableInfo.USER_PASS
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.code,
R.id.name,
};
adapter = new SimpleCursorAdapter(
this, R.layout.activity_login,
CR,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
To display data, you should use ListView and CursorAdapter.
Here is sample code for you: http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html
In that sample code, you can see:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
OnItemClickListener will help you to handle when a item in the listview is clicked.
Hope this will help you.

How to stay in same activity after clicking button in android?

I am trying to develop simple feedback application. When user enters invalid data it should show error. After error is detected all fields should be clear and I should stay on same activity What should I do?Here's my code:
package com.example.feedback;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
public class Feedback extends Activity {
String s;
boolean fill=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
final Button bt1 = (Button) findViewById(R.id.bt1);
final EditText tv2 = (EditText) findViewById(R.id.tv2);
final EditText tv1 = (EditText) findViewById(R.id.tv1);
final EditText tv3 = (EditText) findViewById(R.id.tv3);
final EditText tv4 = (EditText) findViewById(R.id.tv4);
final RadioGroup rg = (RadioGroup) findViewById(R.id.rg1);
bt1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
s = tv1.getText().toString();
check();
s = tv2.getText().toString();
check();
s = tv3.getText().toString();
check();
s = tv4.getText().toString();
check();
if (rg.getCheckedRadioButtonId() == -1){
Toast.makeText(Feedback.this,"Error",Toast.LENGTH_LONG).show();
}
Toast.makeText(Feedback.this,"Press again to Submit",Toast.LENGTH_LONG).show();
bt1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startActivity(new Intent(Feedback.this,Feedback2.class));
// TODO Auto-generated method stub
}
});
// TODO Auto-generated method stub
}
private void check() {
if(s.matches("")){
Toast.makeText(Feedback.this,"Error",Toast.LENGTH_LONG).show();
}
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.feedback, menu);
return true;
}
}
this is the line:
startActivity(new Intent(Feedback.this,Feedback2.class));
after the click, change activity.
I suggest you to check login success in onActivityResult method and if it's true than start new activity

Webview is blank or loading same page for different urls

A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.

Android SQLite Update Query - What Am I Missing

package lab.ex1;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import lab.ex1.HospitalDatabase.Patient;
public class DisplayPatient extends HospitalActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
displayData();
}
private void displayData()
{
final List<Integer> myList = new ArrayList<Integer>();
final Intent me = new Intent(DisplayPatient.this,UpdatePatient.class);
final Bundle b = new Bundle();
//Build new Patient
PatientData build = new PatientData();
final TableLayout viewData = (TableLayout)findViewById(R.id.tblDisplay);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Patient.patientTableName);
SQLiteDatabase db = mDatabase.getReadableDatabase();
String asColumnsToReturn[] = {Patient.patientTableName + "." + Patient.ID,
Patient.patientTableName + "." + Patient.firstName,
Patient.patientTableName + "." + Patient.lastName,
Patient.patientTableName + "." + Patient.room,
Patient.patientTableName + "." + Patient.department};
Cursor c = queryBuilder.query(db,asColumnsToReturn,null,null,null,null,Patient.DEFAULT_SORT_ORDER);
if (c.moveToFirst())
{
for (int i=0; i< c.getCount(); i++)
{
final TableRow newRow = new TableRow(this);
Button update = new Button(this);
TextView display = new TextView(this);
display.setTextSize(15);
update.setX(15);
update.setY(10);
update.setTextSize(10);
Button deleteButton = new Button(this);
deleteButton.setX(100);
deleteButton.setY(100);
deleteButton.setTextSize(10);
deleteButton.setText("Delete");
update.setText("Update");
deleteButton.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
update.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
newRow.setTag(c.getInt(c.getColumnIndex(Patient.ID))); // set the tag field on the TableRow view so we know which row to delete
myList.add(c.getInt(c.getColumnIndex(Patient.ID)));
build.setID(Integer.parseInt(c.getString(c.getColumnIndex((Patient.ID)))));
build.setFirstName((c.getString(c.getColumnIndex(Patient.firstName))));
build.setLastName(c.getString(c.getColumnIndex(Patient.lastName)));
build.setDepartment(c.getString(c.getColumnIndex(Patient.department)));
build.setRoom(Integer.parseInt(c.getString(c.getColumnIndex(Patient.room))));
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer id = (Integer) v.getTag();
deletePatient(id);
final TableLayout patientTable = (TableLayout) findViewById(R.id.tblDisplay);
View viewToDelete = patientTable.findViewWithTag(id);
viewData.removeView(viewToDelete);
}
});
update.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = (Integer)v.getTag();
final TableLayout patientRmv = (TableLayout)findViewById(R.id.tblDisplay);
for (Integer delete : myList )
{
View viewToDelete = patientRmv.findViewWithTag(delete);
viewData.removeView(viewToDelete);
}
b.putString("key", Integer.toString(id));
me.putExtras(b);
startActivity(me);
}
});
display.setText(build.toString());
newRow.addView(display);
newRow.addView(update);
//newRow.addView(deleteButton);
viewData.addView(newRow);
c.moveToNext();
}
}
else
{
TableRow newRow = new TableRow(this);
TextView noResults = new TextView(this);
noResults.setText("No results to show.");
newRow.addView(noResults);
viewData.addView(newRow);
}
c.close();
db.close();
}
public void deletePatient(Integer id)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
String astrArgs[] = { id.toString() };
db.delete(Patient.patientTableName, Patient.ID+ "=?",astrArgs );
db.close();
}
}
package lab.ex1;
import lab.ex1.HospitalDatabase.Patient;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class UpdatePatient extends HospitalActivity {
Spinner spinner;
TextView update;
String up;
Button check;
EditText entry;
String setPosition;
TextView updateID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatepatient);
check = (Button)findViewById(R.id.btnUpdate);
entry = (EditText)findViewById(R.id.editUpdate);
updateID = (TextView)findViewById(R.id.txtIDUpdate);
Bundle accept = getIntent().getExtras();
up = accept.getString("key","0");
updateID.setText(null);
updateID.setText("ID: " + up);
update = (TextView)findViewById(R.id.txtUpdateMessage);
update.setText(null);
// update.setText(up);
spinner = (Spinner) findViewById(R.id.spnChoice);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.arrFields, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateDB(entry.getText().toString(),setPosition,up);
}
});
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> adapterView,
View view, int pos, long id) {
update.setText(null);
update.setText("I will update On " + adapterView.getItemAtPosition(pos).toString());
setPosition = adapterView.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public void updateDB(String valuesToUpdate, String field,String ID)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
db.beginTransaction();
try
{
ContentValues updatePatient = new ContentValues();
if (field == "First Name")
{
updatePatient.put(Patient.firstName, valuesToUpdate);
String astrArgs[] = { up.toString() };
db.update(Patient.patientTableName,updatePatient, Patient.ID+"=?", astrArgs);
//
db.setTransactionSuccessful();
}
}
finally
{
db.endTransaction();
}
db.close();
Intent me = new Intent(UpdatePatient.this,DisplayPatient.class);
startActivity(me);
}
}
I am using Android SQLite Database. In my display class, it reads all the entries from the database and displays them along with an update button next to each entry. That entries update button's tag has entries Patient.ID. When the user clicks update, they are taken to the update class where they can select what they want to update, First Name, Last Name, Apartment, Room. Afterward they click update, to which they are taken back to the Display class and they should see there changes. However, when they are taken back, the previous value is still there, the changes do not show up, what am I missing?
Move your displaydata() call from onCreate to onResume.

Retrieve item from Spinner and put Some conditions

i have 2 arrays first for Hours and second for minutes, this is my arrays declare it in string.xml
` <string-array name="feedbacktypelist">
<item>#string/hr0</item>
<item>#string/hr1</item>
<item>#string/hr2</item>
</string-array>
<string-array name="array2">
<item>#string/min5</item>
<item>#string/min10</item>
<item>#string/min15</item>
<item>#string/min20</item>
<item>#string/min25</item>
<item>#string/min30</item>
<item>#string/min35</item>
<item>#string/min40</item>
<item>#string/min45</item>
<item>#string/min50</item>
<item>#string/min55</item>
<item>#string/min59</item>
</string-array>`
and this is my code in java
package lmp.app.pkg;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class CreateNewForm extends Activity implements OnItemSelectedListener {
Button Browse;
ImageView CasePic;
Spinner CaseDurationH, CaseDurationM;
TextView tesst;
RadioGroup GenderSelection;
EditText CaseName, CaseClothes, CaseMoreInfo, CaseAge;
Button Next;
//For Browsering Picture
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_new_form);
//To Call initializer Function
initializer();
//j list
// 1-For Uploading Picture
Browse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
// 1-Name
final MyCase case1 = new MyCase();
case1.setName(CaseName.getText().toString());
// 2-Gender For Group Radio
GenderSelection.clearCheck();
GenderSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio0:
case1.setGender("Male");
break;
case R.id.radio1:
case1.setGender("Female");
break;
default:
break;
}
}
});
//3-Age
String age = CaseAge.getText().toString();
/*int tstnum =case1.getAge();
tesst.setText(tstnum); */
//4-Duration Time
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.feedbacktypelist, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CaseDurationH.setAdapter(adapter);
//5-Case Clothes
case1.setClothes(CaseClothes.getText().toString());
//6-Case More Information
case1.setMoreInfo(CaseMoreInfo.getText().toString());
//Move to 2nd form page
Next= (Button)findViewById(R.id.Next2);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.Next2:
try
{
Intent k = new Intent(CreateNewForm.this, CreateNewForm_2.class);
startActivity(k);
}catch(Exception e){
}
break;
}
}
});
//Spinner
CaseDurationH.setOnItemSelectedListener(new OnItemSelectedListener() {
int i =CaseDurationH.getSelectedItemPosition();
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int i = CaseDurationH.getSelectedItemPosition();
if(i==2){
CaseDurationM.setEnabled(false);
}
String str = parent.getSelectedItem().toString();
if(str.equals("hr0"))
{
}
if(str.equals("hr1"))
{
}
if(str.equals("hr2"))
{
CaseDurationM.setEnabled(false);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });
}
// To initialize the variables
private void initializer() {
// TODO Auto-generated method stub
//This information will be filled by a user
//CasePic = (ImageView) findViewById(R.id.imageView1);
CaseName= (EditText) findViewById(R.id.caseNm);
GenderSelection= (RadioGroup) findViewById(R.id.radioGroup1);
CaseAge= (EditText) findViewById(R.id.caseaage);
tesst= (TextView) findViewById(R.id.textView8);
CaseDurationH= (Spinner) findViewById(R.id.Shr);
CaseDurationM= (Spinner) findViewById(R.id.Smin);
CaseClothes= (EditText) findViewById(R.id.caseClothes);
CaseMoreInfo= (EditText) findViewById(R.id.caseMrInfo);
CasePic = (ImageView) findViewById(R.id.casepic);
Browse = (Button) findViewById(R.id.browseCasePic);
}
//For Uploading Picture
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
//For Uploading Picture
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
i want:
1- retrieve the item in spinner that the user choose it, not the positon
2-if the user choose from spinner1 the item "hr02" then the spinner2 will disable
Thank you for help me, StackOverFlow members your my hero now! :")
use this
String str = parent.getSelectedItem().toString();
if(str.equals("hr2")
{
spinner2.setEnabled(false);
}
Try this:
String str = parent.getSelectedItem().toString();
if (str.equals("hr0")){
//retrieve the item as string
}
if (str.equals("hr1")){
//retrieve the item as string
}
if (str.equals("hr2")){
//retrieve the item as string
//make the 2nd spinner disable
}

Categories

Resources