Intents keep coming back null - java

So Im making a simple organization app and once I getIntent() and set variables to whatever i used .putExtra() on and it just wont transmit the data between views, could it be that I copied the code from a different app I've made and adapted it or what? because when I do getStringExtra
it comes up as null (which i've tested by setting some buttons text to the getStringExtra and it shows up blank)and doesnt have a value. Even though everything should be correct, can someone just look this over please and tell me whats up?
code from main activity
#Override
public void onResume() {
super.onResume();
if(test==1){
Intent itemCreate = getIntent();
itemName = itemCreate.getStringExtra(CreateItem.NAME_TEXT);
itemLocation = itemCreate.getStringExtra(CreateItem.LOCATION_TEXT);
itemDesc = itemCreate.getStringExtra(CreateItem.DESC_TEXT);
items.add(new Item(itemName, itemLocation, itemDesc));
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
// itemNames.add(items.get(items.size()-1).getName());
addItem.setText(itemName);
toast.show();
if(items!=null) {
lv.setAdapter(adapter);
} //toast.show();
}
}
code from sending activity
public void openMainActivity() {
editName = (EditText) findViewById(R.id.itemNameText);
editLoc = (EditText) findViewById(R.id.itemLocationText);
editDesc = (EditText) findViewById(R.id.itemPriceText);
String name = editName.getText().toString();
String location = editLoc.getText().toString();
String desc = editDesc.getText().toString();
Intent itemCreate = new Intent(this, MainActivity.class);
itemCreate.putExtra(NAME_TEXT, name);
itemCreate.putExtra(LOCATION_TEXT, location);
itemCreate.putExtra(DESC_TEXT, desc);
itemCreate.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(itemCreate);
}

In the receiving activity have you tried as follows:
#Override
public void onResume() {
super.onResume();
if(test==1){
Intent itemCreate = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
itemName = itemCreate.getString(CreateItem.NAME_TEXT);
itemLocation = itemCreate.getString(CreateItem.LOCATION_TEXT);
itemDesc = itemCreate.getString(CreateItem.DESC_TEXT);
items.add(new Item(itemName, itemLocation, itemDesc));
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
// itemNames.add(items.get(items.size()-1).getName());
addItem.setText(itemName);
toast.show();
}
if(items!=null) {
lv.setAdapter(adapter);
} //toast.show();
}
}

Try this:
For checking if your string in being received or not, you can use Logcat:
////add this on receiving activity, in Logcat search using the key "aaaaaa"
////if you received it, it will show you the received text in logcat .
String s = getIntent().getStringExtra("NAME_TEXT");
Log.i("aaaaaaa",s);
/////put the key under double quotation/////
public void openMainActivity() {
editName = (EditText) findViewById(R.id.itemNameText);
editLoc = (EditText) findViewById(R.id.itemLocationText);
editDesc = (EditText) findViewById(R.id.itemPriceText);
String name = editName.getText().toString();
String location = editLoc.getText().toString();
String desc = editDesc.getText().toString();
Intent itemCreate = new Intent(this, MainActivity.class);
itemCreate.putExtra("NAME_TEXT", name);
itemCreate.putExtra("LOCATION_TEXT", location);
itemCreate.putExtra("DESC_TEXT", desc);
itemCreate.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(itemCreate);
}
in receiving activity: make sure that getStringExtra does not get null value, you can use the getIntent() method directly.
#Override
public void onResume() {
super.onResume();
if(test==1){
itemName = getIntent().getStringExtra("NAME_TEXT");
itemLocation = getIntent().getStringExtra("LOCATION_TEXT");
itemDesc = getIntent().getStringExtra("DESC_TEXT");
items.add(new Item(itemName, itemLocation, itemDesc));
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
// itemNames.add(items.get(items.size()-1).getName());
addItem.setText(itemName);
toast.show();
if(items!=null) {
lv.setAdapter(adapter);
} //toast.show();
}
}

Related

setTextColor() - Logic Error

Hello I'm Having a problem with my simple Android Application, it can't change the Text Colors in the other Activity which is displayActivity.java Here's my Code sample.
The problem is if the texts are both equal it will change into color greensuccess
but it did change into rederror
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String xy = "ict402.germio.intent";
public static final String xz = "ict402.germio.intent";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send(View view){
EditText a = findViewById(R.id.a);
EditText b = findViewById(R.id.b);
String strx =(a.getText().toString());
String stry =(b.getText().toString());
if (strx.compareToIgnoreCase(stry) == 0)
{
// this line WILL print
Intent i = new Intent(this, displayActivity.class);
String t = ("Case Ignored \n VALUES ARE THE SAME CONGRATS!").toString();
i.putExtra(xy,t);
startActivity(i);
} else {
Intent i = new Intent(this, displayActivity.class);
String y = ("Case Ignored \n VALUES ARE NOT THE SAME SORRY!").toString();
i.putExtra(xz,y);
startActivity(i);
}
}
}
displayActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent i = getIntent();
String message = i.getStringExtra(MainActivity.xy);
TextView t = findViewById(R.id.x);
t.setTextColor(getResources().getColor(R.color.success));
t.setText(message);
Intent o = getIntent();
String msg = o.getStringExtra(MainActivity.xz);
TextView q = findViewById(R.id.x);
q.setTextColor(getResources().getColor(R.color.error));
q.setText(msg);
}
}
There are so many things wrong. Here's a replacement:
public void send(View view) {
String editTextAContents = findViewById(R.id.a).getText().toString();
String editTextBContents = findViewById(R.id.b).getText().toString();
Intent intent = new Intent(this, DisplayActivity.class);
if (editTextAContents.equalsIgnoreCase(editTextBContents)) {
intent.putExtra("message", "Case Ignored \n VALUES ARE THE SAME CONGRATS");
intent.putExtra("error", false);
} else {
intent.putExtra("ict402.germio.intent", "Case Igored \n VALUES ARE NOT THE SAME SORRY!");
intent.putExtra("error", true);
}
startActivity(intent);
}
In DisplayActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent intent = getIntent();
String message = intent.getStringExtra("message");
boolean hasError = intent.getBooleanExtra("error", false);
TextView textView = findViewById(R.id.x);
textView.setText(message);
if (hasError) {
textView.setTextColor(ContextCompat.getColor(this, R.color.error));
} else {
textView.setTextColor(ContextCompat.getColor(this, R.color.success));
}
}
When you populate an Intent's extras, they must have a different name.
When you declare variables, be more verbose instead of naming them x, y, z, a, b, c so they are more readable.
You're not using any conditional logic to determine what color to use.
You need to do something like this:
TextView t = findViewById(R.id.x);
String successMessage = getIntent().getStringExtra(MainActivity.xy);
String errorMessage = getIntent().getStringExtra(MainActivity.xz);
if(successMessage != null){
t.setTextColor(getResources().getColor(R.color.success));
t.setText(successMessage);
}else if(errorMessage != null){
t.setTextColor(getResources().getColor(R.color.error));
t.setText(errorMessage);
}
A better way of doing it is by sending a boolean through the intent to help you determine what color to set. Here is an example:
Intent i = new Intent(this, displayActivity.class);
if (strx.equalsIgnoreCase(stry)){
i.putExtra("message","Case Ignored \n VALUES ARE THE SAME CONGRATS!");
i.putExtra("success", true);
} else {
i.putExtra("message","Case Ignored \n VALUES ARE NOT THE SAME SORRY!");
i.putExtra("success", false);
}
startActivity(i);
And in the other activity, do this:
TextView t = findViewById(R.id.x);
Intent i = getIntent();
String message = getIntent().getStringExtra("message");
boolean success = getIntent().getBooleanExtra("success");
t.setText(message);
t.setTextColor(getResources().getColor(success ? R.color.success : R.color.error));

Calling Class to another activity

I have a second activity that handles all the user input and another activity that handles all the data from the second activity. What I want to do is call a class "SubmitName" from the activity to the second activity so that I dont need to pass the values from second activity to the main activity anymore. Here are the codes..
MainActivity (Where the class "SubmitName" are located and values are passed.)
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button)findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FragActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
Name = (TextView) findViewById(R.id.tvName);
Intent intent = getIntent();
String str = intent.getStringExtra("firstname");
lastname = intent.getStringExtra("lastname");
licensenumber = intent.getStringExtra("licensenumber");
mviolation = intent.getStringExtra("violation");
maplace = intent.getStringExtra("arrestplace");
maddress = intent.getStringExtra("address");
phonenumber = intent.getStringExtra("phonenumber");
contactnumber = intent.getStringExtra("contactnumber");
officername = intent.getStringExtra("officername");
datetime = intent.getStringExtra("datetime");
Name.setText(str);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromLocalStorage();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.TrafficAd:
Intent i = new Intent(this, TrafficAdvisory.class);
this.startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
public void submitName(View view)
{
String name = Name.getText().toString();
String lname = lastname;
String lnumber = licensenumber;
String violation = mviolation;
String aplace = maplace;
String address = maddress;
String pnumber = phonenumber;
String cnumber = contactnumber;
String oname = officername;
String dtime = datetime;
saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
Name.setText("");
}
public void readFromLocalStorage()
{
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
}
public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{
if (checkNetworkConnection())
{
StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if(Response.equals("OK"))
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("lname",lname);
params.put("lnumber",lnumber);
params.put("violation", violation);
params.put("aplace", aplace);
params.put("address",address);
params.put("pnumber",pnumber);
params.put("cnumber",cnumber);
params.put("oname",oname);
params.put("dtime",dtime);
return params;
}
}
;
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
}
SecondActivity (Where inputs are handled and data passing to the mainactivity)
public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{
EditText Name;
Button btnClose;
TextView DTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violator_detail);
DTime = (TextView)findViewById(R.id.tvDTime);
final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
DTime.setText(currentDT);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(this);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText Name = (EditText)findViewById(R.id.etfName);
EditText LName = (EditText)findViewById(R.id.etlName);
EditText LNumber = (EditText)findViewById(R.id.etlNumber);
EditText Violation = (EditText)findViewById(R.id.etViolation);
EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
EditText Address = (EditText)findViewById(R.id.etAddress);
EditText PNumber = (EditText)findViewById(R.id.etpNumber);
EditText CNumber = (EditText)findViewById(R.id.etcNumber);
EditText OName = (EditText)findViewById(R.id.etoName);
String DT = DTime.getText().toString();
Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
intent.putExtra("firstname", Name.getText().toString());
intent.putExtra("lastname", LName.getText().toString());
intent.putExtra("licensenumber", LNumber.getText().toString());
intent.putExtra("violation", Violation.getText().toString());
intent.putExtra("arrestplace", Arrestplace.getText().toString());
intent.putExtra("address", Address.getText().toString());
intent.putExtra("phonenumber", PNumber.getText().toString());
intent.putExtra("contactnumber", CNumber.getText().toString());
intent.putExtra("officername", OName.getText().toString());
intent.putExtra("datetime", DT);
startActivity(intent);
}
});
}
}
What I want to do is call the "SUBMITNAME" class to the second activity so that no data passing will be done anymore.
As other friends mentioned Intent is a correct and good way to transfer data between activities. But if you want to avoid writing so much code to transfer data I suggest to create a pure java class (or java bean) and define all needed fields in that class (note: this class should implement java.io.Serializable interface). Now you could transfer instances of this class between activities.
I don’t think there is a better way of passing data between activities than Intents.
What you probably need is encapsulation of passing of extra. You can achieve this by making a static method in the ViolatorDetail class, which accepts as arguments as values you would like to pass, and returns Intent.
public static Intent newIntent(Context packageContext, String ... args){
Intent intent = new Intent(packageContext, ViolatorDetail.this);
intent.putExtra(EXTRA_STRING_ARGS, args);
return intent;
}
Then in the caller class you make an intent by makeing a static call on that function, and pass values as arguments
Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);
However, in your case, you should probably make a more sensible way of passing data than as array of strings.
If you don't want to pass data between Activities with Intent, you can do it by writing certain data in a file and when you need it just read from it... I did it like this and I'm still happy i did it that way, it's simple and relatively quick, you just have to care a little about IOExceptions.

Passing value from ListView to another Activity/Class [duplicate]

This question already has answers here:
How to pass an object from one activity to another on Android
(35 answers)
Closed 6 years ago.
So here I have class ListProductActivity.java that display list of products based on the search criteria entered by user and the data are retrieve from MySQL server using Json. My question is, how can I pass a single value (productName in this case) when user select from the listview to another activity so that I can use that value in the new Activity (viewProductActivity.java).
ListProductActivity.java
public class ListProductActivity extends AppCompatActivity {
private ListView list;
private ProgressDialog loading;
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_product);
list = (ListView) findViewById(R.id.listView);
productList = new ArrayList<HashMap<String,String>>();
getData();
}
public void getData(){
String s = getIntent().getStringExtra("productName");
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL2 + s;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showList(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListProductActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showList(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray products = jsonObject.getJSONArray(Config.JSON_ARRAY);
for(int i=0;i<products.length();i++){
JSONObject productData = products.getJSONObject(i);
String name = productData.getString(KEY_NAME);
String price = productData.getString(KEY_PRICE);
String brand = productData.getString(KEY_BRAND);
HashMap<String,String> product = new HashMap<String,String>();
product.put(KEY_NAME,name);
product.put(KEY_PRICE,price);
product.put(KEY_BRAND,brand);
productList.add(product);
}
ListAdapter adapter = new SimpleAdapter(
ListProductActivity.this, productList, R.layout.list_product,
new String[]{KEY_NAME,KEY_PRICE,KEY_BRAND},
new int[]{R.id.name, R.id.price, R.id.brand}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So, what function can I implement in my ListProductActivity class to pass the productName based on user selected in the listView to another activity and how to receive the passing value in viewProductActivity class?
I really hope you guys can post the function and briefly explain on how it works, so that I can understand the codes really well. Comment at the codes will be more clear and helpful. Thank You.
Edited
Here is the picture of the result from the listview after searching
Click To View Image
First simply implement onItemClickListener of listview on current activity
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String product_name = productList.get(position).get(KEY_NAME);
Intent intent = new Intent(YourCurrentActivity.this,YourNextActivity.class);
intent.putExtra("product_name",product_name);
startActivity(intent);
}
});
and receive that value in onCreate method of YourNextActivity.java like this:
Bundle bundle = getIntent().getExtras();
String productname = bundle.getString("product_name");
Implement like this,
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = productList.get(position).get(KEY_NAME);
Intent i;
i = new Intent(mContext, viewProductActivity.class);
i.putExtra("productName",name);
startActivity(i);
}
});
Pass the array list to the new activity later you can use whatever you want from that extra
eg:-
Intent i = new Intent(ctx, SecondActivity.class);
i.putExtra("List", List); //List is an arraylist like yours
startActivity(i);
Second activity:
SList = (ArrayList<HashMap<String,String>>) getIntent().getSerializableExtra("List");
Now use whatever you want using SList.get(0).get("keyname")
put your code here
private void showList(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray products = jsonObject.getJSONArray(Config.JSON_ARRAY);
for(int i=0;i<products.length();i++){
JSONObject productData = products.getJSONObject(i);
String name = productData.getString(KEY_NAME);
String price = productData.getString(KEY_PRICE);
String brand = productData.getString(KEY_BRAND);
HashMap<String,String> product = new HashMap<String,String>();
product.put(KEY_NAME,name);
product.put(KEY_PRICE,price);
product.put(KEY_BRAND,brand);
productList.add(product);
}
ListAdapter adapter = new SimpleAdapter(
ListProductActivity.this, productList, R.layout.list_product,
new String[]{KEY_NAME,KEY_PRICE,KEY_BRAND},
new int[]{R.id.name, R.id.price, R.id.brand}
);
list.setAdapter(adapter);
// put your new code here
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String product_name = productList.get(position).get(KEY_NAME);
Intent intent = new Intent(YourCurrentActivity.this,YourNextActivity.class);
intent.putExtra("product_name",product_name);
startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
You can pass it via Intent in your listview adapter as
Intent i;
i = new Intent(mContext, viewProductActivity.class);
i.putExtra("productName",whateverstring);
mContext.startActivity(i);

Passing values to activities and reciveving them in url

I am trying to receive an integer in url.
This how i pass value from one activity to another:
private void displayCategoriesInformation(CategoriesModel categoriesModel) {
//get references to your views
TextView tvCategoryId = (TextView) findViewById(R.id.tvCategoryId);
final int categoryId = categoriesModel.getId();
//set values from your categoriesModel java object to textView
tvCategoryId.setText("Id : " + categoriesModel.getId());
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Categories.this, SubCategories.class);
intent.putExtra("parameter_name", categoryId);
startActivity(intent);
}
});
}
in SubCategory.class i receive it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_subcategory);
Intent intent = getIntent();
int recivedId = intent.getIntExtra("parameter_name", 2);
TextView tvRecivedId = (TextView) findViewById(R.id.tvRecivedId);
tvRecivedId.setText("recivedId" + recivedId);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
spinnerFood = (Spinner) findViewById(R.id.spinFood);
okButton = (Button) findViewById(R.id.bOk);
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
new JSONTask().execute("http://146.185.178.83/resttest/subCategories");
}
now the value is stored in the variable recivedId which is 1 or 2 or 3 or 4
what i want to do is execute this JSONTask url like this
new JSONTask().execute("http://146.185.178.83/resttest/categories/recivedId/subCategories");
so the end url would look like this http://146.185.178.83/resttest/categories/1/subcategories/
how can i achieve this
String url = "http://146.185.178.83/resttest/categories/" + recivedId +"/subcategories/";
new JSONTask().execute(url);

Android SQLite database seems to clear every time i open a new activity

I've been trying to fix these two bugs for a while and I feel like it has to do with a fundamental misunderstanding of what happens when I open up a new activity. Basically the program is a task management program. It works fine when I add new tasks without modifying the category, and the database updates fine and the main page of the application updates as I add new tasks to display these new tasks.
However, I recently added functionality for an "add categories" button. The purpose of this button is to open up a new listactivity that allows users to add new categories of tasks. Every time I open this from the task editing activity and then press the back button to get back to the main page, all of the tasks in the database get cleared. Wondering if anyone can tell me what's going on and why the data is getting wiped out.
here's the relevant code snippet from the front page (the list view showing all of the tasks:
private RemindersDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder_list);
mDbHelper = new RemindersDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter reminders =
new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
setListAdapter(reminders);
}
Here's some of the code for my task editing view (the one calling the activity for the category listing):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
//mCatDbHelper = new CategoriesDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
//mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mLowPriorityButton = (Button) findViewById(R.id.low_priority);
mMedPriorityButton = (Button) findViewById(R.id.med_priority);
mHighPriorityButton = (Button) findViewById(R.id.high_priority);
mManageCategories = (Button) findViewById(R.id.manage_categories);
mSchoolRadio = (RadioButton)findViewById(R.id.radio_schoolwork);
mFamilyRadio = (RadioButton)findViewById(R.id.radio_family);
mOtherRadio = (RadioButton)findViewById(R.id.radio_other);
mContext = this;
priority = "Low";
category = "Other";
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
registerButtonListenersAndSetDefaultText();
}
private void setRowIdFromIntent() {
if (mRowId == -1L) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
}
#Override
protected void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
protected void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
//if(mRowId != -1L)
populateFields();
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != -1L) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
category = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_CATEGORY));
if(category.equals("School"))
mSchoolRadio.setChecked(true);
else if(category.equals("Family"))
mFamilyRadio.setChecked(true);
else
mOtherRadio.setChecked(true);
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mRowId == -1L)
mRowId = -1L;
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
*/
private void saveState() {
String title = mTitleText.getText().toString();
//String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == -1L) {
long id = mDbHelper.createReminder(title, priority, category, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, priority, category, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
Here's the call (in the same class as the above code) to the new CategoryListActivity activity that's causing the problems:
mManageCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(mContext, CategoryListActivity.class);
startActivity(i);
//populateFields();
}
});
I left out a lot of the less relevant code. Anyway like I said above... the main problem is that as soon as I start this new CategoryListActivity activity, the database and all the tasks get wiped out. weirdly, even if I restart the emulator the tasks don't get wiped as long as I don't start the CategoryListActivity. If anyone has any idea what's going on please help.
Andrew checkout this two links that will explain you everything about database integration.
http://www.devx.com/wireless/Article/40842/1954
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Categories