Android File Read - android

package com.callout.project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.callout.project.Mylocation.LocationResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WorksActivity extends Activity {
/** Called when the activity is first created. */
Mylocation myLocation = new Mylocation();
TextView rtv;
String id;
String strloc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Bundle ext = getIntent().getExtras();
id = (String) ext.get("registration_id");
Log.w("rid", id);
findCurrentLocation();
rtv = (TextView)findViewById(R.id.rtv);
rtv.setText("Thank you For Registering");
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("myfile")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
Log.w("Hello","123"+line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Log.w("file","msg"+line);
// sendtoserver(id,strloc);
}
private void findCurrentLocation() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
if (location != null) {
strloc = location.getLatitude() + ","
+ location.getLongitude();
Log.w("works",strloc);
// TODO Auto-generated method stub
AlertDialog malert = new AlertDialog.Builder(WorksActivity.this).create();
malert.setTitle("here"+strloc);
Log.w("func","in func"+id);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.funnystrippers.co.cc/test.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Rid", "56"));
nameValuePairs.add(new BasicNameValuePair("location","strloc"));
nameValuePairs.add(new BasicNameValuePair("content", "hello frm android"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.w("res",response.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
malert.show();
}
}
};
}
I have this following code which deals with the C2DM, its working fine , but i want the value of Log.w("Hello","123"+line); to be printed outside the try {}
catch block when I do so it gives me error I should get the value printed in my LogCat !!!

line goes out of scope once you leave the try block since it's declared inside of it.
To fix it just move the declaration of line outside the try block and it will still be visible once you leave the block.
String line;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("myfile")));
StringBuffer buffer = new StringBuffer();

Related

Read txt from url using AsyncTask and use it as string in main thread

I have read txt file from URL but cannot use read text from URL to string in main thread. I have the following code.
How can i get string read from AsyncTask in main thread?
package np.info.mukesh.utdlive;
/**
* Created by Mukesh on 4/30/2017.
*/
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.thin.downloadmanager.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
public class LoadActivity extends AppCompatActivity {
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load);
new GetMethodDemo().execute("http://m.live.mukesh.info.np/link.txt");
//Toast data read from url
Toast.makeText(this,server_response(), Toast.LENGTH_LONG).show();
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView tv = (TextView) findViewById(R.id.updateNotice);
tv.setText(server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
I have been searching solution for some days but no luck. I am learning android from stackoverflow and google and some blog post. So, I am not much experienced. Thank you!

How to print the entire JSON output?

Please have a look at the following code
package com.example.jsontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText editText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
//Call The JSon
try {
JSONObject jObject = new JSONObject(getJson());
int code = jObject.getInt("code");
editText.append("Code: "+code+"\n");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getJson()
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://bigml.io/andromeda/source/5277b1bd035d074e940056e0?username=xxx;api_key=xxxxxxxxxxxxxxx");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
}
In here, what I need to do is, print the "entire" result I retrieved. I wish to print the entire thing, I don't need to get separate values. How can I do this? Here is the link to the BigML retrieve documentation.
Just use JSONObject.toString() ?
You should never connect to network on main thread. Best and the most simple option is to use AsyncTask<...>.
something like this:
private class DownloadProductsTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return new PublicDataDBManager().retriveJsonData(mCode, mUserMail);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result){
buildData(result);// here you update mathod in your main thread
}
}
Here is simple example: http://androide-examples.blogspot.com/2013/11/android-retrieve-json-data-from-url.html
So I ran your code, and it crashed. I also see that you are bypassing security and doing network operations in onCreate, in the main thread. This isn't a good idea in Android. Network operations should go in a background thread.
I refactored it very quickly to use a thread and it worked. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new Thread(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(getJson());
// I am logging the raw value that was returned here
Log.i("JSON Body", jObject.toString());
int code = jObject.getInt("code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
If you want to update the main thread (MainActivity) within the thread, create a Handler and pass a reference to that into the thread, and use that for updates.

Read URI on Android

I'm trying to read website data with my Android app. What's strange is that it works on my Android 2.3.4 phone, but not my brand new 2nd Gen Nexus 7 Tablet that's running Android 4.3. I'm not getting any errors in LogCat, there's just nothing displayed on the Tablet. Has anyone else run into this? If so, clue me in to a fix so that it'll run on both my devices. Here's my whole Activity:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WCBCCalendar extends Activity {
Button back_BTN;
TextView urlTest_TV;
String about_url_Str = "http://www. url to read";
String returned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
back_BTN = (Button) findViewById(R.id.backCal_btn);
sunDate_TV = (TextView) findViewById(R.id.sunDate_TV);
npDate_TV = (TextView) findViewById(R.id.npDate_TV);
urlTest_TV = (TextView) findViewById(R.id.urlTest_tv);
GetWebInfo test = new GetWebInfo();
try {
returned = test.getInternetData();
urlTest_TV.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// --- END onCreate
// --- Classes, Methods
public class GetWebInfo {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI(about_url_Str);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity ().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) !=null ){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}//--- END class
// --- END all Classes, Methods
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
}

Android app doesn't want do HttpClient request

I'm trying to launch first app that handles Http requests. The following code is from a tutorial book and it doesn't work:
package com.example.httpgetdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader in = null;
System.out.println("Before");
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://google.com/");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
What do I mean by saying it doesn't work - I run in it on a phone and LogCat shows the first System.out.println but not the second one, there is error saying:
E/(1755): Can't open file for reading
I read some threads over here about making it in asynchronous way, but if so, then the app would crash and, what-more, it's a book example so it should work, shouldn't it? The aim phone runs the ICS
What's wrong?
Thanks

how to upload the image into server

i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}

Categories

Resources