Browse Author: abhijit.kurlekar

How to ObjectSerializer in to java to store in shared preference in Android


public class ObjectSerializer {

// private static final Log log = LogFactory.getLog(ObjectSerializer.class);

public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();

for (int i = 0; i > 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}

return strBuf.toString();
}

public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}

}

How to store the object in to database(Java Serializable Object to Byte Array)

The best way to do it is to use ApacheUtils:

To Serialize:

byte[] data = SerializationUtils.serialize(yourObject);

deserialize:

YourObject yourObject = (YourObject) SerializationUtils.deserialize(byte[] data)

SerializationUtils Class:

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationUtils{
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}

public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
}

Voice Recording in Android

Put below code into your main Activity.

private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonHandlers();
enableButtons(false);
setFormatButtonCaption();
}

private void setButtonHandlers() {
((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
}

private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}

private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnFormat, !isRecording);
enableButton(R.id.btnStop, isRecording);
}

private void setFormatButtonCaption() {
((Button) findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")");
}

private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecording() {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}

private void displayFormatDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = { "MPEG 4", "3GPP" };
builder.setTitle(getString(R.string.choose_format_title)).setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
setFormatButtonCaption();
dialog.dismiss();
}
}).show();
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
@Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};

private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart: {
Toast.makeText(AudioRecordingActivity.this, "Start Recording", Toast.LENGTH_SHORT).show();
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop: {
Toast.makeText(AudioRecordingActivity.this, "Stop Recording", Toast.LENGTH_SHORT).show();
enableButtons(false);
stopRecording();
break;
}
case R.id.btnFormat: {
displayFormatDialog();
break;
}
}
}
};

How to Add Smiley/Emojis in Edittext?

 

Emoji.java :-

package com.android.emoji;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Emoji extends Activity implements OnClickListener {
EditText edttxtemoji;
Button btnsubmit, btnselectemoji;
TextView txtviewdisplay;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edttxtemoji = (EditText) findViewById(R.id.edttxtemoji);
btnsubmit = (Button) findViewById(R.id.btnok);
btnsubmit.setOnClickListener(this);
btnselectemoji = (Button) findViewById(R.id.btnselect);
btnselectemoji.setOnClickListener(this);
txtviewdisplay = (TextView) findViewById(R.id.txtviewdisplay);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == btnsubmit) {
txtviewdisplay.setText(edttxtemoji.getText());
} else if (v == btnselectemoji) {
Intent in = new Intent(this, Select_Emoji_Activity.class);
startActivity(in);
}
}

CharSequence cs;
Custom_List_Emoji cstlistemoji;
int index;

@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();

cstlistemoji = new Custom_List_Emoji(this);
@SuppressWarnings("static-access")
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
this.MODE_WORLD_READABLE);
index = myPrefs.getInt("key1", 0);
System.out.println("Pref Data index is:- " + index);
ImageGetter imageGetter = new ImageGetter() {
public Drawable getDrawable(String source) {
Drawable d = getResources().getDrawable(
cstlistemoji.images[index]);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
cs = Html.fromHtml(
"", imageGetter, null);
System.out.println("cs is:- " + cs);
edttxtemoji.setText(cs);
}
}

Select_Emoji_Activity.java :-

package com.android.emoji;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class Select_Emoji_Activity extends Activity implements OnItemClickListener{
ListView lstviewemojis;
Custom_List_Emoji cstlistemoji;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.emojis);
lstviewemojis=(ListView)findViewById(R.id.lstviewemojis);
lstviewemojis.setOnItemClickListener(this);
cstlistemoji=new Custom_List_Emoji(this);
lstviewemojis.setAdapter(cstlistemoji);
}
@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
System.out.println("Emoji is:- " +arg2);
prefsEditor.putInt("key1", arg2);
prefsEditor.commit();
finish();
}
}

Custom_List_Emoji :-

package com.android.emoji;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class Custom_List_Emoji extends BaseAdapter {

public Activity context;
public LayoutInflater inflater;

public Custom_List_Emoji(Activity context) {
// TODO Auto-generated constructor stub
this.context = context;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return emojis.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
String temp = emojis[position];
return temp;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

TextView txtview1;
ImageView image;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_emojis, null);
txtview1 = (TextView) convertView.findViewById(R.id.txtviewemojis);
image = (ImageView) convertView.findViewById(R.id.imgviewemoji);
}

image.setImageResource(images[position]);
txtview1.setText(emojis[position]);
return convertView;
}

 

public final int[] images = new int[] { R.drawable.emo_im_happy,
R.drawable.emo_im_sad, R.drawable.emo_im_winking,
R.drawable.emo_im_tongue_sticking_out, R.drawable.emo_im_surprised,
R.drawable.emo_im_kissing, R.drawable.emo_im_yelling,
R.drawable.emo_im_cool, R.drawable.emo_im_money_mouth,
R.drawable.emo_im_foot_in_mouth, R.drawable.emo_im_embarrassed,
R.drawable.emo_im_angel, R.drawable.emo_im_undecided,
R.drawable.emo_im_crying, R.drawable.emo_im_lips_are_sealed,
R.drawable.emo_im_laughing, R.drawable.emo_im_wtf };
public final String[] _strEmoticonLabels = new String[] { "Happy", "Sad",
"Winking", "Tongue sticking out", "Surprised", "Kissing",
"Yelling", "Cool", "Money Mouth", "Foot in mouth", "Embarrased",
"Angel", "Undecided", "Crying", "Lips are sealed", "Laughing",
"Confused" };
public final String[] emojis = new String[] { ":-)", ":-(", ";-)", ":-P",
"=-O", ":-*", ":O", "B-)", ":-$", ":-!", ":-[", "O:-)", ":-\",
":'(", ":-X", ":-D", "o_O" };

Facebook Style Slide Menu In Android

Create a new android project in eclipse(Minimum Required Android SKD 2.2 ).

Download slider.jar file from https://s3.amazonaws.com/oodles-site-files/slider.jar.

Place slider.jar in lib folder in project

Now our basic project structure is ready and its time to focus on layouts, replace main.xml code from given one

Create two Android XML Files one for left menu and other for right menu say “left_menu.xml” and “right_menu.xml”.

There are some pre defined funstions in “slider.jar” which help us to create fb style slide menu.

* setLeftBehindContentView(left_layout) is used to set left menu.

* setRightBehindContentView(right_layout) is used to set right menu.

* toggleLeftDrawer() is used to show the left menu.

* toggleRightDrawer() is used to show the right menu.

package com.example.slide_menu;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.navdrawer.SimpleSideDrawer;

public class MainActivity extends Activity {
SimpleSideDrawer slide_me;
Button left_button, right_button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slide_me = new SimpleSideDrawer(this);
slide_me.setLeftBehindContentView(R.layout.left_menu);
slide_me.setRightBehindContentView(R.layout.right_menu);

left_button = (Button) findViewById(R.id.left_buton);
right_button = (Button) findViewById(R.id.right_buton);
left_button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
slide_me.toggleLeftDrawer();
}
});
right_button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
slide_me.toggleRightDrawer();
}
});
}
}

Android Adding Music to your App

Hello guys today I’d like to discuss how I got the music to play in the splash screen here. First off, create a MediaPlayer object.

1> MediaPlayer song = MediaPlayer.create(context, reid);

It takes in a context, in our case of Splash.this – the class is known as splash. And the “reid” is where the song is located. The song should be in the resource(res) folder. Add a new folder where you will be keeping all your sound. It should finally look like:

To start the song you use:

1> song.start();

And because this was a splash screen, the song had to end when the splash screen ends or pauses. So, at the onPause() method I added:

1> song.release();

And that will end the song.

package com.learning.gilo;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;

public class Splash extends Activity{

MediaPlayer song;

protected void onCreate(Bundle b){
super.onCreate(b);

setContentView(R.layout.splash);

song = MediaPlayer.create(Splash.this, R.raw.door); //the song is door.mp3
song.start();

Thread mythread = new Thread(){
public void run(){
try{
sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent myIntent = new Intent("com.learning.gilo.MENULIST");
startActivity(myIntent);
}
}

};

mythread.start();

}

protected void onPause(){
super.onPause();
song.release();
finish();
}
}

How to retrieve installed application list and permissions

In this short post i will show you how use the PackageManager class to retrieve the list of installed applications and associated permissions on your android device .

Starting from the your Activity context you can obtain an instance of PackageManager through the method called getPackageManager(). Using that class is it possible to get a list of ApplicationInfo objects containing details about apps such as MetaData, Permissions, Services or Activities.

Useful data are for example the name of the app, the packageName used to retrieve additional information with PackageManager methods and the publicSourceDir that represent a simple way to identify system or user applications.

The following code gets first of all the PackageManager object, retrieves ApplicationInfos of available apps and for each of them loads the list of permissions and the associated icon as Drawable object.

PackageManager pm = getPackageManager();
List packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo applicationInfo : packages) {
Log.d(TAG, "App:"+applicationInfo.name+" Package :" + applicationInfo.packageName);
try {

PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);

//Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;

if(requestedPermissions != null)
{
for (int i = 0; i < requestedPermissions.length; i++) {
Log.d(TAG,requestedPermissions[i]);
}
}

//Get Application Icon
Drawable appIcon = pm.getApplicationIcon(applicationInfo.packageName);

} catch (NameNotFoundException e) {
e.printStackTrace();
}
}

Incoming mails notification on android

I am looking for a way to programmatically intercept incoming emails on Android, no matter their source (gmail, exchange, IMAP, etc.). My main concern is to have a look at the mail headers rather than the mail body. It can be done for GMail only using the following code –

ContentResolver cr = getContentResolver();
Cursor unread = cr.query(Uri.parse("content://gmail-ls/conversations/xxxxxx@gmail.com"), null, "label:^u", null, null);
unread.moveToFirst();
int subjectIdx = unread.getColumnIndex("subject");

do {
String subject = unread.getString(subjectIdx);
} while (unread.moveToNext());

Is somethink like this available to non-gmail accounts? I know that theoretically I can ask the user for the username and password and connect via imap, but I can’t do it from the business aspect.

Any solution that is possible will be welcome, i.e. Java SDK, NDK, undocumented API or whatever means necessary.

Android Read Excel File from Website and display using a ListView

n this example we start the activity by making a HTTP request to read the Excel file hosted on a Web Server. We take help of the AsyncTask to fetch the data in background from the Excel file using the URL pointing to it. The input stream from the file is then parsed using the Apache POI classes and stored in an ArrayList. After the AsyncTask is completed, basically the complete Excel file is downloaded and parsed it is then displayed using a ListView.

Android Activity – ReadExcelFromUrlActivity.java

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import android.app.Activity;
import android.widget.ArrayAdapter;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.ListView;
import android.widget.Toast;

public class ReadExcelFromUrlActivity extends Activity {

private String LOG_TAG = "ReadExcelFromUrl";
ArrayList shoppingCartList;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//URL path for the Excel file
String url = "http://demo.mysamplecode.com/Servlets_JSP/demoFiles/ExcelOrderFile.xls";
excelURL(url);

}

private void displayCart() {

//Array list of countries
List myList = new ArrayList();
for(int i = 0, l = shoppingCartList.size(); i < l; i++){
ShoppingCart shoppingCart = shoppingCartList.get(i);
String myData = shoppingCart.getItemNumber() + ": " +
shoppingCart.getDescription() + "nPrice: $" +
shoppingCart.getPrice() + "nQuantity: " +
shoppingCart.getQuantity();
myList.add(myData);
}

//Display the Excel data in a ListView
ArrayAdapter dataAdapter = new ArrayAdapter(this,
R.layout.data_list, myList);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);

}

public void excelURL(String url) {
Log.v(LOG_TAG, url);
new ExcelURL().execute(url);
}

private class ExcelURL extends AsyncTask {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private ProgressDialog dialog = new ProgressDialog(ReadExcelFromUrlActivity.this);

protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}

protected String doInBackground(String... urls) {

String URL = null;

try {

URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

HttpGet httpGet = new HttpGet(URL);
response = httpclient.execute(httpGet);

StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
parseExcel(response.getEntity().getContent());
} else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
cancel(true);
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
cancel(true);
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();
cancel(true);
}

return content;
}

protected void onCancelled() {
dialog.dismiss();
Toast toast = Toast.makeText(ReadExcelFromUrlActivity.this,
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();

}

protected void onPostExecute(String content) {
dialog.dismiss();
displayCart();
}

private void parseExcel(InputStream fis){

shoppingCartList = new ArrayList();

try{

// Create a workbook using the Input Stream
HSSFWorkbook myWorkBook = new HSSFWorkbook(fis);

// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);

// We now need something to iterate through the cells
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){

HSSFRow myRow = (HSSFRow) rowIter.next();
// Skip the first 2 rows
if(myRow.getRowNum() < 2) {
continue;
}

ShoppingCart shoppingCart = new ShoppingCart();

Iterator cellIter = myRow.cellIterator();
while(cellIter.hasNext()){

HSSFCell myCell = (HSSFCell) cellIter.next();
String cellValue = "";

// Check for cell Type
if(myCell.getCellType() == HSSFCell.CELL_TYPE_STRING){
cellValue = myCell.getStringCellValue();
}
else {
cellValue = String.valueOf(myCell.getNumericCellValue());
}

// Just some log information
Log.v(LOG_TAG, cellValue);

// Push the parsed data in the Java Object
// Check for cell index
switch (myCell.getColumnIndex()) {
case 0:
shoppingCart.setItemNumber(cellValue);
break;
case 1:
shoppingCart.setDescription(cellValue);
break;
case 2:
shoppingCart.setPrice(Double.valueOf(cellValue));
break;
case 3:
shoppingCart.setQuantity(Double.valueOf(cellValue));
break;
default:
break;
}

}

// Add object to list
shoppingCartList.add(shoppingCart);
}
}
catch (Exception e){
e.printStackTrace();
}

}

}
}

Shopping cart Java object – ShoppingCart.java

public class ShoppingCart {

String itemNumber = null;
String description = null;
Double price = null;
Double quantity = null;

public String getItemNumber() {
return itemNumber;
}
public void setItemNumber(String itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}

}

Android Manifest file

NullPointerException when going back through activities(In TabGroupActivity)

A little elaboration.

There are Activity A, B and C

You start A with Id “A”
then you start B with Id “B”
then you start C with Id “C”
and from C you again start another instance of B with id “B” (it may happen, because B may be a ResultListScreen which may called for several time with Load More type button)

The problem is that in ArrayList idList when you finish from last B

manager.destroyActivity( idList.get( index ), true );

line is called which destroys Activity having id “B”, which are 2 in stack. both B are deleted and C is pushed. and when you finish C and there is no B in the stack but its Id is available is ArrayList idList and you get its Activity which is null if not found.

That’s all.

id+=System.currentTimeMillis();

in this line of code you assign a unique id every time you start new Activity by using System’s current time.

You Can use this to solve your problem.


public void startChildActivity(String id, Intent intent) {
id+=System.currentTimeMillis();
//rest of your code.
}

  • 1
  • 2

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at info@nanostuffs.com, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box