.setOnItemClicklistener not works - android

I would like to send my data from one activity to other with help of intent and uri but the task doesnt get accomplished
my main activity code
package com.example.vidit.inventoryapp;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import static android.R.attr.id;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
/** Identifier for the pet data loader */
private static final int ITEM_LOADER = 0;
/** Adapter for the ListView */
ItemCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,editor.class);
startActivity(intent);
}
});
ListView ItemListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
ItemListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of pet data in the Cursor.
// There is no pet data yet (until the loader finishes) so pass in null for the Cursor.
mCursorAdapter = new ItemCursorAdapter(this, null);
ItemListView.setAdapter(mCursorAdapter);
// Setup the item click listener
ItemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Create new intent to go to {#link EditorActivity}
Intent intent = new Intent(MainActivity.this,editor.class);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
intent.setData(itemUri);
startActivity(intent);
}
});
// Kick off the loader
getLoaderManager().initLoader(ITEM_LOADER, null, this);
}
private void insertPet() {
// Create a ContentValues object where column names are the keys,
// and Toto's pet attributes are the values.
ContentValues values = new ContentValues();
values.put(ItemContract.ItemEntry.NAME, "Football");
values.put(ItemContract.ItemEntry.PRICE, 200);
values.put(ItemContract.ItemEntry.STATUS, ItemContract.ItemEntry.ACCEPTED);
values.put(ItemContract.ItemEntry.QUANTITY, 7);
// Insert a new row for Toto into the provider using the ContentResolver.
// Use the {#link PetEntry#CONTENT_URI} to indicate that we want to insert
// into the pets database table.
// Receive the new content URI that will allow us to access Toto's data in the future.
Uri newUri = getContentResolver().insert(ItemContract.ItemEntry.CONTENT_URI, values);
}
/**
* Helper method to delete all pets in the database.
*/
private void deleteAllPets() {
int rowsDeleted = getContentResolver().delete(ItemContract.ItemEntry.CONTENT_URI, null, null);
Log.v("CatalogActivity", rowsDeleted + " rows deleted from pet database");
}
#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);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ItemContract.ItemEntry._ID,
ItemContract.ItemEntry.NAME,
ItemContract.ItemEntry.PRICE,
ItemContract.ItemEntry.QUANTITY,
};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
ItemContract.ItemEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
My adapter class:
package com.example.vidit.inventoryapp;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import static android.R.attr.id;
import static android.R.attr.order;
import static android.R.attr.value;
import static android.os.Build.VERSION_CODES.M;
public class ItemCursorAdapter extends CursorAdapter {
public ItemCursorAdapter(Context context, Cursor c) {
super(context, c, 0 /* flags */);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate a list item view using the layout specified in list_item.xml
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView priceTextView = (TextView) view.findViewById(R.id.price);
final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity);
Button sell=(Button) view.findViewById(R.id.sell);
Button order=(Button) view.findViewById(R.id.order);
Button detail =(Button) view.findViewById(R.id.detail);
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.NAME);
int priceColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.QUANTITY);
// Read the attributes from the Cursor for the current pet
String itemName = cursor.getString(nameColumnIndex);
String itemPrice = cursor.getString(priceColumnIndex);
final String itemQuantity=cursor.getString(quantityColumnIndex);
if (TextUtils.isEmpty(itemPrice)) {
itemPrice = "Not known yet";
}
if (TextUtils.isEmpty(itemQuantity)) {
itemPrice = "Not known yet";
}
final int qua=Integer.parseInt(itemQuantity);
nameTextView.setText(itemName);
priceTextView.setText(itemPrice);
quantityTextView.setText(itemQuantity);
sell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Integer.parseInt(itemQuantity)>0)
{
int x=Integer.parseInt(itemQuantity)-1;
quantityTextView.setText("" + x);
int idColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry._ID);
int id = cursor.getInt(idColumnIndex);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
ContentValues values = new ContentValues();
values.put(ItemContract.ItemEntry.QUANTITY, x);
context.getContentResolver().update(itemUri, values, null, null);
}
}
});
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
context.startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
});
/* view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,editor.class);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
intent.setData(itemUri);
context.startActivity(intent);
}
});*/
}
}
if I add intent code which i have commented in adapter class itnet happens succesfully but no data is passed from list view to the intent .
Thanks in advance.

Related

Handling clicks inside listview

I'm new in Android and need help with my ListView, which contains text view and image in every list item. I need handle clicks on list item and on icon (R.id.list_star) in list item separately. I tried several ways but it seems I can't do it by myself. I tried to put star.setOnItemClickListener in the beginning, near lvData.setOnItemClickListener - but in this case view isn't found, and add swith inside AdapterView.OnItemClickListener - doesn't work. My code handles only list item click but no icon clicks
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class ListViewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
ListView lvData;
DB db;
SimpleCursorAdapter scAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
db = new DB(this);
db.open();
String[] from = new String[]{DB.COLUMN_IMG, DB.COLUMN_TXT, DB.COLUMN_IMG2};
int[] to = new int[]{R.id.list_label, R.id.list_text, R.id.list_star};
scAdapter = new SimpleCursorAdapter(this, R.layout.list_item, null, from, to, 0);
lvData = (ListView) findViewById(R.id.list);
lvData.setAdapter(scAdapter);
getSupportLoaderManager().initLoader(0, null, this);
lvData.setOnItemClickListener(mOnListItemClickListener);
}
final Context context = this;
protected void onDestroy() {
super.onDestroy();
db.close();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
return new MyCursorLoader(this, db);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
scAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class MyCursorLoader extends CursorLoader {
DB db;
public MyCursorLoader(Context context, DB db) {
super(context);
this.db = db;
}
#Override
public Cursor loadInBackground() {
Cursor cursor = db.getAllData();
return cursor;
}
}
private AdapterView.OnItemClickListener mOnListItemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Cursor cursor = (Cursor) scAdapter.getItem(position);
switch (v.getId()) {
case R.id.list_star:
Toast.makeText(getApplicationContext(), "star", Toast.LENGTH_SHORT).show();
case R.id.list_label:
Toast.makeText(getApplicationContext(), "label", Toast.LENGTH_SHORT).show();
}
ImageView star = (ImageView) findViewById(R.id.list_star);
star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Вы выбрали стихи Агнии Барто", Toast.LENGTH_SHORT).show();
}
});
Intent intent = new Intent(context, ViewPagerActivity.class);
String pos = Long.toString(position);
intent.putExtra("pos", pos);
startActivity(intent);
}
};
}

AsyncTaskLoader's onStartLoading() isnt being called

I have this custom Loader that is supposed to insert some dummy data I sent to it in a database using content resolver. I'm using the getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this);
in the activity. The constructor gets called. But the onStartLoading() and loadinBackgroung() arent called.
Here is the ProductInsertionLoader.java
public class ProductInsertionLoader extends AsyncTaskLoader {
private String LOG_TAG = ProductInsertionLoader.class.getSimpleName();
private ArrayList<ContentValues> mValues;
private ContentResolver mContentResolver;
public ProductInsertionLoader(Context context, ContentResolver contentResolver, ArrayList<ContentValues> values) {
super(context);
mValues = values;
mContentResolver = contentResolver;
Log.v(LOG_TAG, "constructor called");
}
#Override
public Object loadInBackground() {
Log.v(LOG_TAG, "loadInBackground() called");
ArrayList<Uri> uris = new ArrayList<>();
for (ContentValues value : mValues) {
Uri uri = mContentResolver.insert(ProductContract.ProductEntry.CONTENT_URI, value);
Log.v(LOG_TAG, "Dummy data inserted. ID: " + ContentUris.parseId(uri));
uris.add(uri);
}
return null;
}
#Override
protected void onStartLoading() {
Log.v(LOG_TAG, "onStartLoading() called");
forceLoad();
}
}
Here is how I'm calling it in the CatalogActivity.java
package com.example.android.inventory;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.inventory.data.ProductContract.ProductEntry;
import com.example.android.inventory.data.ProductInsertionLoader;
import java.io.IOException;
import java.util.ArrayList;
public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = CatalogActivity.class.getSimpleName();
private ProductCursorAdapter mCursorAdapter;
private static final int URL_LOADER = 0;
private static final int INSERT_DUMMY_DATA_ID = 1;
private Uri mCurrentProductUri;
private ArrayList<ContentValues> mValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
final ListView listView = (ListView) findViewById(R.id.list_view_product);
TextView textView = (TextView) findViewById(R.id.empty_view);
listView.setEmptyView(textView);
mCursorAdapter = new ProductCursorAdapter(this, null, getContentResolver());
listView.setAdapter(mCursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
Uri currentProductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
intent.setData(currentProductUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(URL_LOADER, null, CatalogActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_insert_dummy_data:
insertDummyData();
return true;
case R.id.action_delete_all_entries:
showDeleteConfirmationDialog("Delete all products?", null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void insertDummyData() {
mValues = new ArrayList<>();
mValues.add(getContentValues("Sugar", 50, 60, "Sweet Sugar Company", R.drawable.sugar));
mValues.add(getContentValues("Salt", 20, 30, "Salty Salt Company", R.drawable.salt));
mValues.add(getContentValues("Bread", 45, 20, "Nanglo", R.drawable.bread));
mValues.add(getContentValues("Biscuit", 75, 20, "GoodDay", R.drawable.biscuit));
mValues.add(getContentValues("Noodles", 15, 200, "CupMen", R.drawable.noodles));
mValues.add(getContentValues("Milk", 33, 100, "DDC", R.drawable.milk));
mValues.add(getContentValues("Cheese", 80, 30, "Amul", R.drawable.cheese));
getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this).forceLoad();
Toast.makeText(this, "Dummy Data Inserted", Toast.LENGTH_SHORT).show();
}
private ContentValues getContentValues(String name, int price, int quantity, String supplier, int resId) {
ContentValues values = new ContentValues();
values.put(ProductEntry.COLUMN_NAME, name);
values.put(ProductEntry.COLUMN_PRICE, price);
values.put(ProductEntry.COLUMN_QUANTITY, quantity);
values.put(ProductEntry.COLUMN_SUPPLIER, supplier);
//Uri for the sugar drawable
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(resId)
+ '/' + getResources().getResourceTypeName(resId)
+ '/' + getResources().getResourceEntryName(resId));
Bitmap bitmap = null;
//Converting the sugar image into a thumbnail
try {
bitmap = DbBitmapUtility.getThumbnail(imageUri, this);
} catch (IOException e) {
e.printStackTrace();
}
//Converting the sugar thumbnail into a byte array.
byte[] image = DbBitmapUtility.getBitmapAsByteArray(bitmap);
values.put(ProductEntry.COLUMN_IMAGE, image);
return values;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case URL_LOADER:
String[] projection = {
ProductEntry._ID,
ProductEntry.COLUMN_NAME,
ProductEntry.COLUMN_QUANTITY,
ProductEntry.COLUMN_PRICE,
ProductEntry.COLUMN_SUPPLIER,
ProductEntry.COLUMN_IMAGE
};
return new CursorLoader(
this,
ProductEntry.CONTENT_URI,
projection,
null,
null,
null);
case INSERT_DUMMY_DATA_ID:
new ProductInsertionLoader(this, getContentResolver(), mValues);
return null;
default:
Log.v(LOG_TAG, "onCreateLoader: Invalid id");
return null;
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == URL_LOADER) {
mCursorAdapter.swapCursor(data);
} else return;
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
As you can see I'm using two loaders. One CursorLoader to load all the database data into the UI, and a second custom AsyncTaskLoader to insert some dummy data on to the database on a background thread.
Why isn't the custom loader's onStartLoading() or loadInBackground() not being called?

SQLite database and ListView not syncing up properly, off by 1 number

I'm having trouble with my database and I can't seem to track down the problem. I'm an Android noob.
Whenever I add a term or delete a term, the data seems to be loading for the wrong listview item that I click on.
I had to modify the id before sending it to the intent to try to fix it but I keep getting errors.
Here is my datasource code:
package com.mikero.termtracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import java.util.ArrayList;
import java.util.List;
public class DataSource {
//Fields
private SQLiteDatabase db;
private DBOpenHelper helper;
private String[] allTermColums = {DBOpenHelper.KEY_ID, DBOpenHelper.NAME_OF_TERM,
DBOpenHelper.TERM_START_DATE, DBOpenHelper.TERM_END_DATE};
public DataSource(Context context){
helper = new DBOpenHelper(context);
}
public void open() throws SQLiteException{
db = helper.getWritableDatabase();
}
public void close(){
helper.close();
}
//Create Term
public Term createTerm(Term term){
ContentValues cv = new ContentValues();
cv.put(DBOpenHelper.NAME_OF_TERM, term.getTermsName());
cv.put(DBOpenHelper.TERM_START_DATE, term.getTermStartDate());
cv.put(DBOpenHelper.TERM_END_DATE, term.getTermEndDate());
long insertId = db.insert(DBOpenHelper.TERMS_TABLE, null, cv);
term.setId(insertId);
return term;
}
//Update term
public void update(Term term){
long id = term.getId();
ContentValues cv = new ContentValues();
cv.put(DBOpenHelper.NAME_OF_TERM, term.getTermsName());
cv.put(DBOpenHelper.TERM_START_DATE, term.getTermStartDate());
cv.put(DBOpenHelper.TERM_END_DATE, term.getTermEndDate());
db.update(DBOpenHelper.TERMS_TABLE, cv, DBOpenHelper.KEY_ID + " = " + id, null);
}
//CursorToTerm method
private Term cursorToTerm(Cursor cursor){
Term term = new Term();
term.setId(cursor.getLong(0));
term.setTermsName(cursor.getString(1));
term.setTermStartDate(cursor.getString(2));
term.setTermEndDate(cursor.getString(3));
return term;
}
//Getting all terms
public List<Term> getAllTerms(){
List<Term> termList = new ArrayList<>();
Cursor cursor = db.query(DBOpenHelper.TERMS_TABLE, allTermColums,
null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Term term = cursorToTerm(cursor);
termList.add(term);
cursor.moveToNext();
}
cursor.close();
return termList;
}
//Getting and creating a single term
public Term getSingleTermById(long id){
Cursor cursor = db.query(DBOpenHelper.TERMS_TABLE, allTermColums,
DBOpenHelper.KEY_ID + " = ?",
new String[] {String.valueOf(id)}, null, null, null);
if (cursor != null){
cursor.moveToFirst();
}
Term term = cursorToTerm(cursor);
return term;
}
//Getting a single term by id
// public Cursor getTermById(long id){
// Cursor cursor = db.query(DBOpenHelper.TERMS_TABLE, allTermColums,
// DBOpenHelper.KEY_ID + " = ?",
// new String[] {String.valueOf(id)}, null, null, null);
// return cursor;
// }
//Delete single term
public void deleteTerm(Term term){
long id = term.getId();
db.delete(DBOpenHelper.TERMS_TABLE, DBOpenHelper.KEY_ID + " = " + id, null);
}
//Delete single term by id
public void deleteTermById(long id){
db.delete(DBOpenHelper.TERMS_TABLE, DBOpenHelper.KEY_ID + " = " + id, null);
}
}
Here is my TermViewActivity:
package com.mikero.termtracker;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class TermViewActivity extends AppCompatActivity {
public static final String EXTRA_TERMNO = "termNo";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_term_view);
//Get term id from intent
final long termNo = (Long) getIntent().getExtras().get(EXTRA_TERMNO);
//Create a cursor
DBOpenHelper helper = new DBOpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query(DBOpenHelper.TERMS_TABLE, new String[]{DBOpenHelper.KEY_ID,
DBOpenHelper.NAME_OF_TERM,
DBOpenHelper.TERM_START_DATE, DBOpenHelper.TERM_END_DATE},
DBOpenHelper.KEY_ID + " = ?",
new String[]{String.valueOf(termNo)}, null, null, null);
if (cursor.moveToFirst()) {
//Get all the info to populate TextViews
String nameOfTerm = cursor.getString(1);
String termStartDate = cursor.getString(2);
String termEndDate = cursor.getString(3);
//Populate first textview
TextView textView1 = (TextView) findViewById(R.id.textview_term_name);
textView1.setText(nameOfTerm);
//Populate second textview
TextView textView2 = (TextView) findViewById(R.id.textview_term_start_date);
textView2.setText(termStartDate);
//Populate third textview
TextView textView3 = (TextView) findViewById(R.id.textview_term_end_date);
textView3.setText(termEndDate);
}
cursor.close();
db.close();
//Set listener
Button deleteButton = (Button) findViewById(R.id.delete_term_button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(TermViewActivity.this);
alertDialog.setTitle("Delete Confirmation");
alertDialog.setMessage("Are you sure you want delete this?");
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DataSource ds = new DataSource(getApplicationContext());
ds.open();
// ds.deleteTermById(termNo);
Term term = ds.getSingleTermById(termNo);
ds.deleteTerm(term);
ds.close();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("TermView Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
Here is my TermActivity:
package com.mikero.termtracker;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class TermActivity extends ListActivity {
private DataSource ds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_term);
ds = new DataSource(this);
ds.open();
setAdapter();
}
#Override
public void onRestart(){
super.onRestart();
finish();
startActivity(getIntent());
}
public void onClick(View view){
ArrayAdapter<Term> adapter = (ArrayAdapter<Term>)getListAdapter();
Term term = null;
switch(view.getId()){
case R.id.addButton:
Intent intent = new Intent(getApplicationContext(), TermEditActivity.class);
startActivity(intent);
break;
}
}
#Override
public void onListItemClick(ListView listView,
View itemView,
int position,
long id){
id = id+1L;
Intent intent = new Intent(getApplicationContext(), TermViewActivity.class);
intent.putExtra(TermViewActivity.EXTRA_TERMNO, id);
startActivity(intent);
}
public ArrayAdapter<Term> setAdapter(){
List<Term> termList = ds.getAllTerms();
ArrayAdapter<Term> adapter = new ArrayAdapter<Term>(this,
android.R.layout.simple_list_item_1, termList);
setListAdapter(adapter);
return adapter;
}
}
I can only figure one of my methods in my DataSource is wrong, or perhaps I'm using the wrong code somewhere between the two Activities.
in TermActivity, you need to get the id by the position of item in Adapter, not the id:
#Override
public void onListItemClick(ListView listView,
View itemView,
int position,
long id){
Intent intent = new Intent(getApplicationContext(), TermViewActivity.class);
// get the id of object by its position in
// the adapter
Term term = getListView().getItemAtPosition(position);
long itemId = term.getId();
intent.putExtra(TermViewActivity.EXTRA_TERMNO, itemId);
startActivity(intent);
}

Bug in app while rotating Android phone

hello guys i started to learn to build android applications via udacy. After a long troubleshooting i didnt find something that can cause the bug that i have. the bug is that when i rotate the phone the view seems to clone it self and not deleting the previous one if someone can help me ill be very happy.
1) normal state of app:
2) after rotation:
3) and after another rotation the application crashing
it never happend until i added the code in the xml file of the view:
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for weather forecast list item for future day (not today) -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/list_item_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow"/>
<TextView
android:id="#+id/list_item_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:gravity="right">
<TextView
android:id="#+id/list_item_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="81"
android:paddingLeft="10dp"/>
<TextView
android:id="#+id/list_item_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="68"
android:paddingLeft="10dp"/>
</LinearLayout>
</LinearLayout>
Activity Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private String FORECASTFRAGMENT_TAG = "FFTAG";
String mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new MainActivityFragment(), FORECASTFRAGMENT_TAG)
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mLocation = Utility.getPreferredLocation(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
String location = Utility.getPreferredLocation(this);
if(location != null && location != mLocation){
MainActivityFragment ff = (MainActivityFragment)getSupportFragmentManager().findFragmentById(R.id.fragment);
if(ff != null){
ff.onLocationChanged();
}
mLocation = location;
}
}
#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){
Intent settings = new Intent(this,SettingsActivity.class);
startActivity(settings);
}
if(R.id.action_map == id){
openPreferedLocationMap();
}
return super.onOptionsItemSelected(item);
}
private void openPreferedLocationMap(){
String location = Utility.getPreferredLocation(this);
Uri geoLocation = Uri.parse("geo:0,0?").buildUpon().appendQueryParameter("q",location).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if(intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
else{
Log.d("SHOWING MAP PROBLEMM","could't call"+ location+ "intent");
}
}
}
Fragment Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.andy.sunshine.app.data.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data.
// Specify the columns we need.
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
static final int COL_WEATHER_ID = 0;
static final int COL_WEATHER_DATE = 1;
static final int COL_WEATHER_DESC = 2;
static final int COL_WEATHER_MAX_TEMP = 3;
static final int COL_WEATHER_MIN_TEMP = 4;
static final int COL_LOCATION_SETTING = 5;
static final int COL_WEATHER_CONDITION_ID = 6;
static final int COL_COORD_LAT = 7;
static final int COL_COORD_LONG = 8;
private ForecastAdapter mForecastAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#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();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
String location = Utility.getPreferredLocation(getActivity());
weatherTask.execute(location);
}
public void onLocationChanged(){
updateWeather();
getLoaderManager().restartLoader(FORECAST_LOADER,null,this);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String locationSetting = Utility.getPreferredLocation(getActivity());
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mForecastAdapter.swapCursor(null);
}
}
And Class That Extends CursorAdapter "ForecastAdapter":
package com.example.andy.sunshine.app;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.andy.sunshine.app.data.WeatherContract;
/**
* {#link ForecastAdapter} exposes a list of weather forecasts
* from a {#link android.database.Cursor} to a {#link android.widget.ListView}.
*/
public class ForecastAdapter extends CursorAdapter {
private final int VIEW_TYPE_TODAY = 0;
private final int VIEW_TYPE_FUTURE_DAY = 1;
public ForecastAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getItemViewType(int position) {
return (position == 0)? VIEW_TYPE_TODAY:VIEW_TYPE_FUTURE_DAY;
}
#Override
public int getViewTypeCount() {
return 2;
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(Context context,double high, double low) {
boolean isMetric = Utility.isMetric(mContext);
String highLowStr = Utility.formatTemperature(context,high, isMetric) + "/" + Utility.formatTemperature(context,low, isMetric);
return highLowStr;
}
/*
This is ported from FetchWeatherTask --- but now we go straight from the cursor to the
string.
*/
private String convertCursorRowToUXFormat(Context context,Cursor cursor) {
// get row indices for our cursor
String highAndLow = formatHighLows(context,
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP),
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP));
return Utility.formatDate(cursor.getLong(MainActivityFragment.COL_WEATHER_DATE)) +
" - " + cursor.getString(MainActivityFragment.COL_WEATHER_DESC) +
" - " + highAndLow;
}
/*
Remember that these views are reused as needed.
*/
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int VIEW_TYPE = getItemViewType(cursor.getPosition());
int layoutId = -1;
if(VIEW_TYPE == VIEW_TYPE_TODAY){
layoutId = R.layout.list_item_forecast_today;
}else if(VIEW_TYPE == VIEW_TYPE_FUTURE_DAY){
layoutId = R.layout.list_item_forecast;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
view.setTag(viewHolder);
return view;
}
/*
This is where we fill-in the views with the contents of the cursor.
*/
#Override
public void bindView(View view, Context context, Cursor cursor) {
// our view is pretty simple here --- just a text view
// we'll keep the UI functional with a simple (and slow!) binding.
MyViewHolder viewHolder = (MyViewHolder)view.getTag();
viewHolder.iconView.setImageResource(R.mipmap.ic_launcher);
// TODO Read date from cursor
long dateInMillis = cursor.getLong(MainActivityFragment.COL_WEATHER_DATE);
viewHolder.dateView.setText(Utility.getFriendlyDayString(context, dateInMillis));
// TODO Read weather forecast from cursor
viewHolder.descriptionView.setText(cursor.getString(MainActivityFragment.COL_WEATHER_DESC));
// Read user preference for metric or imperial temperature units
boolean isMetric = Utility.isMetric(context);
// Read high temperature from cursor
double high = cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP);
viewHolder.highTempView.setText(Utility.formatTemperature(context,high, isMetric));
// TODO Read low temperature from cursor
double low = cursor.getDouble(MainActivityFragment.COL_WEATHER_MIN_TEMP);
viewHolder.lowTempView.setText(Utility.formatTemperature(context,low, isMetric));
}
public static class MyViewHolder {
public final ImageView iconView;
public final TextView dateView;
public final TextView descriptionView;
public final TextView highTempView;
public final TextView lowTempView;
public MyViewHolder(View view){
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
dateView = (TextView)view.findViewById(R.id.list_item_date_textview);
descriptionView = (TextView)view.findViewById(R.id.list_item_forecast_textview);
highTempView = (TextView)view.findViewById(R.id.list_item_high_textview);
lowTempView = (TextView)view.findViewById(R.id.list_item_low_textview);
}
}
}
if you want to see the whole project and check maybe for errors that may cause that i posting here my github https://github.com/obruchkov/Sunshine with all the code that i did. please help me guys

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#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_detais_rest, 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.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#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_quentity, 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);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

Categories

Resources