To shorten the URL using google api - android

Hi i am using an example to make a url shorten. But cant able to do that, here's my code
package com.tinyurl;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
public class tinyurl extends Activity implements OnClickListener {
EditText original;
TextView txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.Button01);
original = (EditText) findViewById(R.id.edittext);
txt = (TextView) findViewById(R.id.TextView03);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAau1E_WrYwMiTNqhK5hgH0tyWudyahbOI";
String tinyUrl = null;
String original = "http://www.google.com/";
HttpTransport transport = GoogleTransport.create();
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonHttpParser());
HttpRequest request = transport.buildPostRequest();
request.setUrl(GOOGL_URL);
GenericData data = new GenericData();
// data.put("longUrl", "http://www.google.com/");
data.put("longUrl", original);
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
HttpResponse response = null;
try {
response = request.execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("eception occured", e.toString());
}
Result result = null;
try {
result = response.parseAs(Result.class);
Log.d("TinyUrl", result.shortUrl.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class Result extends GenericJson {
public String shortUrl;
}
}
but the thing is i am getting in Log is java.net.UnknownHostException:www.googleapis.com

You have to modify AndroidManifest.xml to grant permission of "android.permission.INTERNET"
Info from: http://android-er.blogspot.com/2011/09/query-and-parse-google-json.html

This looks a network issue. Use the code given here to access a website using java network api http://www.coderanch.com/t/440335/sockets/java/Access-website-Java-Code
This will allow you to track the actual error and once that is fixed you can use any JSON lib to parse the response from server.

Ah, if you're getting UnknownHostException that means your DNS server is not successfully resolving www.googleapis.com. I'd check to make sure that you actually have a working network connection.

Related

Error when trying to use toast in android application

in my application i am fetching json data from online server. and after that i am trying to display the data by toast. but the application stop working. if i commented the toast section then the application runs smoothly. so i think there is a problem in toast section. so guys plz help me to find out the reason for the problem
package com.example.getdata;
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.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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity {
EditText password,username;
String pass,user;
//TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onConnect(View v) {
new Thread(){
public void run(){
HttpClient myClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://tusharinfotech.com/debasish/get_data.php");
try {
List<NameValuePair> myArgs = new ArrayList<NameValuePair>();
// myArgs.add(new BasicNameValuePair("username", user));
// myArgs.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(myArgs));
HttpResponse myResponse = myClient.execute(post);
BufferedReader br = new BufferedReader( new InputStreamReader(myResponse.getEntity().getContent()));
String line = "";
String data1 ="";
while ((line = br.readLine()) != null)
{
try {
JSONArray myarray = new JSONArray(line);
for(int i=0;i<myarray.length();i++){
JSONObject jsonObject = myarray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("FOOD_ID").toString());
String name = jsonObject.optString("FOOD_NAME").toString();
data1 += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n ";
}
//Log.d("mytag",data);
//this application stop working for this toast part.. if i commented it then the application run smoothly
Toast.makeText(getApplicationContext(),data1, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//EditText output1 = (EditText) findViewById(R.id.editText1);
// output1.setText(data);
Log.d("mytag", line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
I guess you are trying to show toast on a background thread, which is not allowed in android. you can use this code to show toast in background thread :
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
You must display Toast only from UI thread, to workaround this you can get use of runOnUiThread() method or create new Handler and pass in constructor Looper.getMainLoopper()
You could use AsyncTask Framework to make background processing easier http://developer.android.com/reference/android/os/AsyncTask.html.
The method onPostExecute(Result) will be run on your UI thread there for you can change your UI element here.

Android code stop responding when the edit text left empty

hi i am new learner of android and java.below this is my code. I having trouble to know where is the problem.
when i debug few times, it automatically enter debug mode after that. to fix that i have to restart the phone again. I check with other apps, it work just fine. just for the apps that i currently working on.
problem :
1. if i didn't enter data into the "dateTo" the program will stopped.
2. enter debug mode itself.
3. when i get the data from the array atList, then i key in another 'dateTo" to retrieve another data, but it doesn't replace the current data value. tq
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/{API_KEY}/streams/?order=-1&max=2&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
//establish the parameters for the http post request
connection.addRequestProperty("carriots.apikey", "somekey");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
//create a buffered reader to interpret the incoming message from the carriots system
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
//Log.d("returnMsg",returnMsg.toString());
return returnMsg;
}
protected void onPostExecute(String result)
{
//show the message returned from Carriots to the user
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
EditText myData=(EditText)findViewById(R.id.editText2);
myData.setText(atList.get(1));
}
}
}
This line long timeTo = dateTo.getTime(); will throw a NullPointerException when the dateFormatTo.parse method throws a ParseException. This is going to happen when you come into the method with the To string not matching the specified format.
You're not exiting out of the flow so the long...getTime(); line runs, but dateTo is null resulting in a crash.
In the onPostExecute; you aren't verifying that atList has multiple elements. A JSON parse failure will leave atList empty and cause an index bounds exception for those 2 get calls.
These may not be the solutions to what you're seeing; but they will crash the app when these are hit in very likely situations; including the one you describe of an empty string for To.
As the comments mention; the logs will help see what's actually happening; but this is too big for a comment and those points are going to cause problems.

AsyncTask unfortunately stops on second execution

I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.

How to handle - Application has stopped working in Android

So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.

Trying to make my android application put files on my ftp server

I have spent a lot of time trying to make this code work, and in its current state it almost exactly mirrors the code I found at https://stackoverflow.com/questions/3482583/apache-ftpclient-failing-to-download-larger-files. I am also using apache commons net.
for some reason my application never gets past the client.connect step, even when i plug in other IP addresses of ftp servers that should work.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class FtpClientService extends Activity {
//static int fail;
public FtpClientService(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.ftp);
FtpConnect();
}
public static void FtpConnect(){
String userName="usrname";
String passWord = "password";
String ftpAddress = "127.0.0.1"; //this isnt the ip address I was using...
String retrieveFromFTPFolder = "/Pictures/";
String strLine;
DataInputStream inputStream = null;
BufferedReader bufferedReader = null;
FTPClient client = null;
FTPFile[] ftpFiles = null;
int reply;
try{
client = new FTPClient();
client.setListHiddenFiles(true);
client.connect(ftpAddress); //this right here is where it fails
client.login(userName, passWord);
client.setFileType(FTP.BINARY_FILE_TYPE);
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (Exception e) {
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f) {}
}
}
finally{
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f){}
}
}
}
public static void main(String[] args) {
FtpConnect();
}
Thanks in advance!
In the connect method, pass it a constructed InetAddress with appropriate address and port.
Also, don't perform FTP connection on main thread, consider using AsyncTask.
Try using this:
client.connect(InetAddress.getByAddress(ftpAddress,new byte[]{127,0,0,1}));

Categories

Resources