Unable to connect to server through wifi in android - java

I am trying to connect one android device to another using wifi. One device is acting as a server using hotspot. Another device is connected to it. But when I am running the following piece of code, it gives the following exception.
java.net.ConnectException: failed to connect to /192.168.43.198 (port 5555): connect failed: ENETUNREACH (Network is unreachable)
I am using the below files.
HostActivity.java
public class HostActivity extends Activity {
ListView lvHost;
HostAdapter adHost;
final String HostTAG = "Host1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
WifiManager wifiManager = (WifiManager)this.getSystemService (Context.WIFI_SERVICE);
new RetrieveFeedTask2(getApplicationContext()).execute("");
int i =0 ;
lvHost = (ListView) findViewById( R.id.lvHost);
int j = 0;
ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks();
adHost = new HostAdapter(list,this);
lvHost.setAdapter(adHost);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.host, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class RetrieveFeedTask2 extends AsyncTask<String, Context, String> {
Context ctx = null;
public RetrieveFeedTask2(Context Dctx) {
// TODO Auto-generated constructor stub
ctx = Dctx;
}
protected String doInBackground(String ...url) {
final String HostTAG = "Host1";
final WifiManager wifiManager = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
try {
Boolean end = false;
Log.i("test","HostRun");
ServerSocket ss = new ServerSocket(5555);
while(!end){
Log.i("test", "HostRun2");
//Server is waiting for client here, if needed
Socket s = ss.accept();
Log.i("test", "HostRun3");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
Log.i("test", "From client: "+st);
System.out.println("From client: "+st);
//output.println("Good bye and thanks for all the fish :)");
s.close();
// ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks();
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.i("test","host unknown");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
ClientActivity.java
public class ClientActivity extends Activity {
final String ClientTAG = "Client1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
WifiManager wifiManager = (WifiManager)getSystemService("wifi");
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = Formatter.formatIpAddress(ipAddress);
new RetrieveFeedTask().execute(ip);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
}
class RetrieveFeedTask extends AsyncTask<String, String, String> {
//Context context;
protected String doInBackground(String ...urls) {
final String ClientTAG = "Client1";
InetAddress ia=null;
Log.i("test", "ClientRun1");
try {
try {
ia=InetAddress.getLocalHost();
Log.i("test",ia.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Socket s = new Socket("192.168.43.198",5555);
Log.i("test", "ClientRun");
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
String st = input.readLine();
//. . .
//Close connection
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
I tried googling. Many have mentioned same problem and I tried all the solutions but still not able to connect. Please help.

Some suggestions:
Use 10000 < port number <= 65536 in android. (less than 10000,
some errors may occur).
If the mobile network is active, the ServerSocket(port number) uses the outgoing IP (mobile network's IP). Try ServerSocket(int port, int backlog, InetAddress localAddress) instead.(You need to specify an address, that is, hotspot's address.)
In ClientActivity.java, I see you pass an IP through execute(ip), but you didn't use it. You can do Socket s = new Socket(ip,5555);.
AsyncTask is not recommended for doing a long time work. Use Thread instead.

Related

Endless RecyclerView with ProgressBar in Search activity

I am new at android. I have a search activity which searches for a query using async task, i want to implement endless/infinite scrolling when user reaches bottom. I want to add a parameter startrow to async task which will then be passed on to the server telling which row to begin.
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private LinearLayoutManager mLayoutManager;
private String searchQuery;
SearchView searchView = null;
private String query;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
class AsyncFetch which will fetch data from the server
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// URL address wherephp file resides
url = new URL("http://someurl/json/search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
try {
fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
fishData.linkName = json_data.getString("link");
fishData.reg_date = json_data.getString("reg_date");
fishData.fileSize = json_data.getString("filesize");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
// mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRVFish.setLayoutManager(mLayoutManager);
mRVFish.setAdapter(mAdapter);
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Add EndlessScrollListener to recyclerView from link:
https://gist.github.com/zfdang/38ae655a4fc401c99789#file-endlessrecycleronscrolllistener-java
override onLoadMore method and call your AsyncFetch Task.

changing the value of variable in thread while its running

I am building an android app in which service is running and it has a thread which listens for tcp connections and receive the message and respond back.Actually what I want to do is to give the user the choice to respond with yes or no ,when the thread will accept the connection, My service class is this:
public class Receiver extends Service {
static String TCP_RECEIVE = "soft.b.peopleassist";
public static String ip;
DatagramSocket socket;
private WifiManager.WifiLock wifiLock=null;
private PowerManager.WakeLock wakeLock=null;
volatile public static String outgoingMsg="null";
#SuppressLint("DefaultLocale")
public String getIpAddr() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return ipString;
}
private void listenAndWaitAndThrowIntent(Integer port) throws Exception {
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
JSONObject jsonObj = new JSONObject();
try {
jsonObj = new JSONObject(incomingMsg);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String trans=(String) jsonObj.get("TranId");
String ide=(String) jsonObj.get("Amount");
String hashs=(String) jsonObj.get("Basket");
incomingMsg=trans+","+ide+","+hashs;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TcpServer", "received: " + incomingMsg);
//send a message
// String outgoingMsg = "goodbye from port " + port + System.getProperty("line.separator");
// outgoingMsg = "ok";
broadcastIntent(incomingMsg);
incomingMsg=null;
Thread.sleep(3000);
out.write(outgoingMsg);
out.flush();
Log.i("TcpServer", "sent: " + outgoingMsg);
broadcastIntent(incomingMsg);
//SystemClock.sleep(5000);
s.close();
outgoingMsg="null";
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void broadcastIntent(String message) {
Intent intent = new Intent(Receiver.TCP_RECEIVE);
intent.putExtra("messages", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
// InetAddress broadcastIP = InetAddress.getByName(ip); //172.16.238.42 //192.168.1.255
Integer port = 21111;
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent(port);
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
private Boolean shouldRestartSocketListen=true;
void stopListen() {
shouldRestartSocketListen = false;
if(socket!=null)
socket.close();
}
#Override
public void onCreate() {
Log.i("Service", "WiFi lOCK");
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
wifiLock.acquire();
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Lock");
wakeLock.acquire();
};
#Override
public void onDestroy() {
stopListen();
wifiLock.release();
wakeLock.release();
Log.i("UDP", "Service stoped");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("TCP", "Service started");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
outGoingMsg is the message which is actually a response.Now I want the thread to wait until the value of this variable in thread is not changed.There is another class from where I want to change this variable.For now am calling sleep to sleep this thread for few seconds but its not the right way because if after few seconds user don't respond it will automatically send null..please help how can I do this..
you can put the waiting action into an loop, which breaks if the value is set.
for reasons of visibility you should use an volatile modifier.
I'll post an example in a minute.
volatile String valueIAmWaitingFor; // Class Variable
...
while(valueIAmWaitingFor == null){
Thread.sleep(3000);
}
//go on
The other method can now set valueIAmWaitingFor.
volatile:
Declaring a volatile Java variable means: The value of this variable
will never be cached thread-locally: all reads and writes will go
straight to "main memory"; Access to the variable acts as though it
is enclosed in a synchronized block, synchronized on itself.
This is just one way to do this. There are many more secure solutions (but also more complex than this hotfix)
EDIT: of course it has to be valueIAmWaitingFor == null, and not valueIAmWaitingFor != null

Socket not connected in my Android app

I've been working in a server/client application that needs to get the hour from a server working in my computer.
When I try to run this app in my phone it says that SOCKET NOT CONNECTED. I tried everything but it still not working.
The thread is working, but the socket is not connecting!
The permissions I used:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The MainActivity.java is:
package com.example.clientehora;
/* imports */
public class MainActivity extends Activity {
Socket socket = new Socket();
String SERVER_IP = "10.215.19.41";
int SERVERPORT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
#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;
}
public void ejecutar(View view) {
try {
System.out.println("Hola amigo, si me presionaste! =D" + socket.getInetAddress() + socket.getPort());
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String cadena = br.readLine();
System.out.println("LA CADENA ES: " +cadena);
EditText et = (EditText)findViewById(R.id.fecha);
et.setText(cadena);
br.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
System.out.println("Se ha conectado sin problemas");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
This works for me to connect to my Win7 PC via USB (mTimeout is 5000):
mSocket = new Socket();
mSocket.setSoTimeout(mTimeout);
mSocket.connect(new InetSocketAddress(SERVER_IP, SERVERPORT), mTimeout);
I get the IP to use using this command on the PC:
InetAddress.getLocalHost().getHostAddress()

TCP in Android - ObjectOutputStream writeObject failure

I'm trying to send an Object from my phone to my PC(Windows) using a TCP socket via WiFi. When I try the same code between two PCs, it works without any error. But when I put the client code to the android device, it fails to send date using writeObject method. But writeUTF command works. It gives the "Software caused connection abort: recv failed" error. Below is the Code. Please help..
Server(in PC):
public class Test {
public static void main(String arg[]) {
ServerSocket serverSocket = null;
Socket socket = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
System.out.println("ip: " + socket.getInetAddress());
Message msg = (Message) in.readObject(); //Message captured from chat client.
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
out.writeObject(new Message("Ack", "Server", "Message Received", "Client"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Client (in Android Device):
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bb=(Button)findViewById(R.id.button1);
bb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Send().execute();
}
});
}
#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;
}
private class Send extends AsyncTask<Void, Void, Void> {
Socket socket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.43.92", 8888); //use the IP address of the server
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
out.writeObject(new Message("Chat", "Server", "Hello World", "Server")); //This method is used to write something to the server.
out.flush();
Message msg = (Message) in.readObject();
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
}
Message(in Both Sides):
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;
public Message(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}
Is the network between the client and server setup properly via your WiFi? Download one of those ping & telnet test apps and use it to test your network connection.
Telnet is a useful TCP debugging app. If you have a server listening on 11.22.33.44 port 1234, you should be able to telnet 11.22.33.44 1234
Maybe, you need to add this functions into Message class:
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(type);
stream.writeObject(sender);
stream.writeObject(content);
stream.writeObject(recipient);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
type = (String) stream.readObject();
sender = (String) stream.readObject();
content = (String) stream.readObject();
recipient = (String) stream.readObject();
}
http://developer.android.com/reference/java/io/Serializable.html

Convert Text File to String in java

i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.
public class MainActivity extends Activity {
Button b1;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File upfile=new File("sdcard/text/testfile.txt");
try {
FileInputStream fin=new FileInputStream(upfile);
byte[] buffer= new byte[(int)upfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
s=new String(buffer,"UTF-8");
System.out.print(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, s, 20).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
try this.
public void mReadJsonData() {
try {
File f = new File("sdcard/text/testfile.txt");
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use this code to read the data from file and get it into string and do your process ahead according to your need--
File upfile=new File("sdcard/text/testfile.txt");
try {
final BufferedReader reader = new BufferedReader(new FileReader(upfile));
String encoded = "";
try {
String line;
while ((line = reader.readLine()) != null) {
encoded += line;
}
}
finally {
reader.close();
}
System.out.print(encoded);
}
catch (final Exception e) {
}

Categories

Resources