TCP socket connection, receiving and displaying data in list view. - android

I am doing a project of TCP socket connection.
receiving json data from server and display it into a list view.
server sends data continually for every 1 sec.
I am getting an error of index out of bound exception Invalid index 4 size is 4.
My code is as follow.
I think problem is with User u = list.get(position); and runonUIthread.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity{
String str;
ArrayList<User> list = new ArrayList<User>();;
ArrayAdapter<User> adb;
ListView lv;
SQLiteAdapter sqladapter = new SQLiteAdapter(MainActivity.this);;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
lv = (ListView) findViewById(R.id.listView1);
new Thread(new Client()).start();
Timer tm = new Timer();
}
public class Client implements Runnable{
#Override
public void run() {
try {
Socket s = new Socket("My IP",My Port);
while(s.isConnected()){
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
int nRead;
char[] data = new char[1024+512];
String decoded= "";
Date date = new Date();
long time = date.getTime();
while ((nRead = in.read(data, 0, data.length)) != -1) {
decoded += new String(data,0,nRead);
if(decoded.contains("{") && decoded.contains("}")){
str = decoded.substring(decoded.indexOf('{'),decoded.indexOf('}')+1);
decoded = decoded.substring(decoded.indexOf('}')+1);
if(!decoded.contains("{"))
decoded = "";
try {
JSONArray results = new JSONArray("["+str+"]");
for (int i = 0; i < results.length(); i++) {
JSONObject jsonObject;
jsonObject = results.getJSONObject(i);
String symbol = jsonObject.getString("Symbol");
double high = Double.parseDouble(jsonObject.getString("High"));
double low = Double.parseDouble(jsonObject.getString("Low"));
sqladapter = sqladapter.opentowrite();
boolean insertOrUpdate = sqladapter.checkDB(symbol);
if(insertOrUpdate== false){
User user = new User(jsonObject.getString("Symbol"),
jsonObject.getString("AskPrice"),
jsonObject.getString("BidPrice"),
jsonObject.getString("Open"),
jsonObject.getString("High"),
jsonObject.getString("Low"),
jsonObject.getString("Close"),
jsonObject.getString("PerChange"),
jsonObject.getString("NetChange"),
jsonObject.getString("Volume"));
sqladapter.insert(user);
list.add(user);
}
else{
int j;
for(j = 0; j<list.size();j++){
User obj = list.get(j);
if(obj.getSymbol().equalsIgnoreCase(symbol)){
list.remove(obj);
System.out.println("REMOVIED "+obj.getSymbol());
break;
}
}
User user2 = new User(jsonObject.getString("Symbol"),
jsonObject.getString("AskPrice"),
jsonObject.getString("BidPrice"),
jsonObject.getString("Open"),
high+"",low+"",
jsonObject.getString("Close"),
jsonObject.getString("PerChange"),
jsonObject.getString("NetChange"),
jsonObject.getString("Volume"));
list.add(j,user2);
System.out.println("ADDED :"+j);
}
updateList();
runOnUiThread(new Runnable() {
#Override
public void run() {
lv.setAdapter(adb);
adb.notifyDataSetChanged();
lv.invalidateViews();
lv.getCount();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(date.getTime()- time);
}
}
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void updateList() {
adb = new ArrayAdapter<User>(MainActivity.this, R.layout.rssitemview,list){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
if(null == view) {
LayoutInflater vi = (LayoutInflater)MainActivity.this.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
User u = list.get(position);
if(null != u)
{
TextView title = (TextView)view.findViewById(R.id.symbol);
TextView persend = (TextView)view.findViewById(R.id.persent);
TextView ltp = (TextView)view.findViewById(R.id.ltp);
TextView open = (TextView)view.findViewById(R.id.open);
TextView high = (TextView)view.findViewById(R.id.high);
TextView low = (TextView)view.findViewById(R.id.low);
TextView close = (TextView)view.findViewById(R.id.close);
title.setText(u.getSymbol().substring(0, 5));
ltp.setText(u.getPerChange().substring(0, 4));
persend.setText(u.getVolume().substring(0, 4));
open.setText(u.getOpen().substring(0, 4));
high.setText(u.getHigh().substring(0, 4));
low.setText(u.getLow().substring(0, 4));
close.setText(u.getClose().substring(0, 4));
}
return view;
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Please help..

Related

share textview content with whatsapp and facebook

I am using below code and my textview links are clickable but i want to make specific button of whatsapp and facebook for sharing..i referred several article in stackoverflow but i want for textview. for webview i had earlier done and it was easy .please help /suggest for textview sharing. i dont want all buttons to open. i want after each listview one facebook and whatsapp icon. on click whatsapp should open with text to be shared
in textview i am adding below for whatsapp share but nothing happens
<a rel="nofollow" href="whatsapp://send?text=एक वृद्ध दंपति को लगने लगा कि उनकी क वृद्ध दंपति को लगने लगा कि उनकी याददाश्त कमजोर हो चली है। यह सुनिश्चित करने के लिये कि उन्हें कुछ नही%0A."><span class="whatsapp"> </span></a>
my java code is
tried adding this one also in java but no benefit.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
if (intent != null) {
intent.putExtra(Intent.EXTRA_TEXT, msg);
startActivity(Intent.createChooser(intent, ""));
main.java code here
package com.hindishayari.funnywall.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import com.hindishayari.funnywall.R;
import com.hindishayari.funnywall.adapter.SwipeDownListAdapter;
import com.hindishayari.funnywall.analytics.AnalyticsApplication;
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
// URLS for Fetching and Submitting to Funny Wall.
private String FetchFunnyWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/ppppppppp.php";
private String SubmitJokeToWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/hhhhhhhhhh.php";
private InterstitialAd mInterstitialAd;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeDownListAdapter adapter;
private ArrayList<String> jokesList;
private ArrayList<String> timeDateList;
String JokeString = null;
String []dataValues = new String[2];
int counter = 0;
TextView titleTextView;
AlertDialog alertDw;
AlertDialog.Builder builder;
Typeface font;
LinearLayout adViewLayout;
LinearLayout listViewLayout;
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
font = Typeface.createFromAsset(getAssets(), "HelveticaNeue-Regular.ttf");
titleTextView = (TextView) findViewById(R.id.titleID);
adViewLayout = (LinearLayout) findViewById(R.id.adViewLayoutID);
listViewLayout = (LinearLayout) findViewById(R.id.ListViewLinearLayout);
titleTextView.setTypeface(font);
dataValues[0] = "";
dataValues[1] = "";
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
jokesList = new ArrayList<>();
timeDateList = new ArrayList<>();
adapter = new SwipeDownListAdapter(this, jokesList, timeDateList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
}
);
/*
This function is to refresh the List with Swipe-Down
*/
#Override
public void onRefresh() {
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
#Override
protected void onResume() {
super.onResume();
}
/*
This function is to fetch all the jokes + dates from the server and store that into the jokesList
timeDateLis respectively
*/
private class FetchFunnyWallFromServer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return FetchFunnyWall(urls[0]);
} catch (IOException e) {
return "Sorry, We cannot retrieve credits data form the server at this moment.";
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
listView.setEnabled(false);
dataValues[0] = "";
dataValues[1] = "";
counter = 0;
jokesList.clear();
timeDateList.clear();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
swipeRefreshLayout.setRefreshing(false);
listView.setEnabled(true);
if (result.equals("OK")) {
listView.post(new Runnable() {
#Override
public void run() {
Collections.reverse(jokesList);
Collections.reverse(timeDateList);
adapter.notifyDataSetChanged();
listView.smoothScrollToPosition(0);
}
});
}
else
{
Toast.makeText(getApplicationContext(), "Network Connection Problem. Make sure that your internet is properly connected", Toast.LENGTH_SHORT).show();
}
}
}
private String FetchFunnyWall(String myurl) throws IOException, UnsupportedEncodingException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
is = conn.getInputStream();
BufferedReader textReader = new BufferedReader(new InputStreamReader(is));
String readlineText;
while ((readlineText = textReader.readLine()) != null) {
if (readlineText.length() > 0 )
{
if (readlineText.equals("****")) {
continue;
}
if (readlineText.length() < 4) {
continue;
}
for (int i = 0; i < readlineText.length(); ++i) {
if (readlineText.charAt(i) == '|') {
++counter;
continue;
}
dataValues[counter] = (dataValues[counter] + readlineText.charAt(i));
}
jokesList.add(dataValues[0]);
timeDateList.add(dataValues[1]);
counter = 0;
dataValues[0] = "";
dataValues[1] = "";
}
}
}
}
}
any help will be great

How to update ProgressBar with respect to downloaded data while downloading text data from web using Asynctask in android

I want to show progressbar wrt to downloaded data from the web. Whether I have to create dynamically or have to reference by Id by creating it in xml.I am a little bit confused. Here is my code. Could you please tell me how?
package com.example.telugumovies;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String category ="";
String[] cat = {"Upcoming","Telugu"};
private List<String> categories ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categories = new ArrayList<String>();
int i=0;
for(i=0;i<2;i++)
{
categories.add(cat[i]+" Movies");
}
ArrayAdapter<String> myAdapter = new ArrayAdapter <String>(this,
R.layout.listview_rowlayout, R.id.tv, categories);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
Bundle giveCategory = new Bundle();
if(position == 0)
{
try {
new GetData().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
else if(position == 1)
{
giveCategory.putString("cate", cat[position]);
Intent a = new Intent(MainActivity.this,Show_Years.class);
a.putExtras(giveCategory);
startActivity(a);
}
else
{
Toast.makeText(getApplicationContext(), "Sorry This option is not Available for Now ",
Toast.LENGTH_SHORT).show();
}
//String selectedItem = (String) getListView().getItemAtPosition(position);
}
class GetData extends AsyncTask<String,Integer,String>
{
ProgressBar pb ;
protected void onPreExecute()
{
pb = new ProgressBar(MainActivity.this);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String alldata = "";
int flag=1;
String data = "";
URL url = null;
int i=0,j=0,count=0,c=0;
URLConnection con = null;
InputStream is = null;
String line = null;
try
{
url = new URL("http://www.filmibeat.com/telugu/upcoming-movies.html");
con = url.openConnection();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
//System.out.println(line);
alldata = "";
flag=0;
if(line.contains("<h3"))
{j=0;
flag=1;
for(i=0;i<line.length();i++)
{
if(line.charAt(i)=='<')
{
j=1;
}
else if(j==1 && line.charAt(i)=='>')
{
j=0;
}
else if(j==0)
{
alldata = alldata + (line.charAt(i));
}
}
}
data=data+alldata;
if(flag==1)
{
data=data+"$";
}
}
System.out.println(data);
return data;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
return data;
}
}
protected void onPostExecute(String someting)
{
Bundle givedata = new Bundle();
givedata.putString("moviedata",someting);
Intent a = new Intent(MainActivity.this,Show_upcomingmovies.class);
a.putExtras(givedata);
pb.setVisibility(View.INVISIBLE);
startActivity(a);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Using dynamically created progress bar or referencing it from an id, are both fine.
Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well.
There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted():
pDialog = new ProgressDialog(this);
pDialog.setMessage("some downloading massage");
pDialog.setIndeterminate(false);
pDialog.setMax(100); //you can adjust this
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();

XML parsing from local xml

I'm parsing XML from URL. What changes has been made to parse same XML file from raw folder. Have any idea to how to reduce code ?
This my xml file :umesh.xml
<?xml version="1.0" encoding="utf-8"?>
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<product>Gloves</product>
</brand>
<brand name="Great Things">
<product>Table</product>
<product>Chair</product>
<product>Bed</product>
</brand>
</appdata>
Below is my java file :
DataHandler.java
package com.umesh.xmlparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.util.Log;
import android.widget.TextView;
public class DataHandler extends DefaultHandler{
//list for imported product data
private ArrayList<TextView> theViews;
//string to track each entry
private String currBrand = "";
//flag to keep track of XML processing
private boolean isProduct = false;
//context for user interface
private Context theContext;
//constructor
public DataHandler(Context cont) {
super();
theViews = new ArrayList<TextView>();
theContext = cont;
}
//start of the XML document
public void startDocument () { Log.i("DataHandler", "Start of XML document"); }
//end of the XML document
public void endDocument () { Log.i("DataHandler", "End of XML document"); }
//opening element tag
public void startElement (String uri, String name, String qName, Attributes atts)
{
//handle the start of an element
//find out if the element is a brand
if(qName.equals("brand"))
{
//set product tag to false
isProduct = false;
//create View item for brand display
TextView brandView = new TextView(theContext);
brandView.setTextColor(Color.rgb(73, 136, 83));
//add the attribute value to the displayed text
String viewText = "Items from " + atts.getValue("name") + ":";
brandView.setText(viewText);
//add the new view to the list
theViews.add(brandView);
}
//the element is a product
else if(qName.equals("product"))
isProduct = true;
}
//closing element tag
public void endElement (String uri, String name, String qName)
{
//handle the end of an element
if(qName.equals("brand"))
{
//create a View item for the products
TextView productView = new TextView(theContext);
productView.setTextColor(Color.rgb(192, 199, 95));
//display the compiled items
productView.setText(currBrand);
//add to the list
theViews.add(productView);
//reset the variable for future items
currBrand = "";
}
}
//element content
public void characters (char ch[], int start, int length)
{
//process the element content
//string to store the character content
String currText = "";
//loop through the character array
for (int i=start; i<start+length; i++)
{
switch (ch[i]) {
case '\\':
break;
case '"':
break;
case '\n':
break;
case '\r':
break;
case '\t':
break;
default:
currText += ch[i];
break;
}
}
//prepare for the next item
if(isProduct && currText.length()>0)
currBrand += currText+"\n";
}
public ArrayList<TextView> getData()
{
//take care of SAX, input and parsing errors
try
{
//set the parsing driver
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
//create a parser
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
SAXParser xmlParser = parseFactory.newSAXParser();
//get an XML reader
XMLReader xmlIn = xmlParser.getXMLReader();
//instruct the app to use this object as the handler
xmlIn.setContentHandler(this);
//provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
URL xmlURL = new URL("http://mydomain.com/umesh.xml");
//open the connection and get an input stream
URLConnection xmlConn = xmlURL.openConnection();
InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
//build a buffered reader
BufferedReader xmlBuff = new BufferedReader(xmlStream);
// uuu XmlResourceParser todolistXml = getResources().getXml(R.raw.c4mh_clinics);
//parse the data
xmlIn.parse(new InputSource(xmlBuff));
}
catch(SAXException se) { Log.e("AndroidTestsActivity",
"SAX Error " + se.getMessage()); }
catch(IOException ie) { Log.e("AndroidTestsActivity",
"Input Error " + ie.getMessage()); }
catch(Exception oe) { Log.e("AndroidTestsActivity",
"Unspecified Error " + oe.getMessage()); }
//return the parsed product list
return theViews;
}
}
XMLParsing.java
package com.umesh.xmlparsing;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsing extends Activity {
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get a reference to the layout
LayoutInflater inflater = getLayoutInflater();
LinearLayout mainLayout = (LinearLayout) inflater.inflate(R.layout.main,null);
try
{
//create an instance of the DefaultHandler class
//**ALTER THIS FOR YOUR CLASS NAME**
DataHandler handler = new DataHandler(getApplicationContext());
//get the string list by calling the public method
ArrayList<TextView> newViews = handler.getData();
//convert to an array
Object[] products = newViews.toArray();
//loop through the items, creating a View item for each
for(int i=0; i<products.length; i++)
{
//add the next View in the list
mainLayout.addView((TextView)products[i]);
}
}
catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
setContentView(mainLayout);
}
}
Please See below link of my answer, it will solve your problem.
Local XML Parsing

symbol variable R.raw not find in android

I am developing an application in which i need to read a resource file. I am saving my file (named "sample")in raw directory of res folder. When i tried to access it in code, by writing its resource id as R.raw.sample , it gives the following error.
Error(30,60)Cannot find symbol variable raw.
I am using intellij idea 11.0.3 and platform for android is 2.3.3.
The code is as follows...
package com.example;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SampleLoader {
public SampleLoader(){
}
public static int[] readFromFile(Context ctx, int resId){
String sample = readRawTextFile(ctx,resId);
int [] arr = stringToIntArray(sample);
return arr;
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader buffReader = new BufferedReader(inputReader);
String line;
StringBuilder text = new StringBuilder();
try {
//while (( line = buffReader.readLine()) != null) {
if (( line = buffReader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public static int[] stringToIntArray(String line){
int[] sample = new int[line.length()-2];
String s ;
for (int i=0; i<line.length(); i++)
{
if(i>1)
{ sample[i] = Character.getNumericValue(line.charAt(i));
}
}
return sample;
}
public void populateListOfSamples(){
}
}
package com.example;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(createContent());
}
LinearLayout createContent(){
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
linearLayout.setLayoutParams(params);
final int[] arr6 = SampleLoader.readFromFile(this,R.raw.sample) ;
final Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.no3);
final ImageView imageView1 = new ImageView(this);
imageView1.setVisibility(View.INVISIBLE);
final TextView textView = new TextView(this);
String str2 = "Byte Array will appear here!";
textView.setText(str2);
final Button btn2 = new Button(this);
final Button btn = new Button(this);
btn.setText("Convert Pic to Byte Array");
btn.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
textView.setText(str3);
btn2.setVisibility(View.VISIBLE);
}
});
btn2.setText("Convert Byte Array to Pic");
btn2.setVisibility(View.INVISIBLE);
btn2.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
btn.setVisibility(View.INVISIBLE);
final Bitmap imag = filing.arrtoimg(arr6);
textView.setVisibility(View.INVISIBLE);
imageView1.setVisibility(View.VISIBLE);
imageView1.setImageBitmap(imag);
}
});
linearLayout.addView(imageView1);
linearLayout.addView(btn);
linearLayout.addView(btn2);
linearLayout.addView(textView);
return linearLayout;
}
}

toast mesage not shown on screen when network or server not available

I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.

Categories

Resources