开始编写一个简单的 android 应用程序。其中一部分是提取用户最后 20 条推文并将它们保存到数据库中。当我运行它时, statuses = twitter.getUserTimeline(); 抛出一个异常处理并打印出来:未能获得时间线权限被拒绝。当我在非 android 上运行相同的代码时,它工作正常。我有点困惑。android会限制网络连接吗?我使用了一些数据库助手类,没有包含代码,因为在涉及任何这些之前抛出异常:(这是代码:
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class TwitterTest extends ListActivity{
private ArrayList<String> queryString;
private DatabaseQuery query;
/* returns date in string format-without time */
String getThisYearDate(Date d){
String x = d.toString();
String y= x.substring(0, 11);
String z =x.substring(17);
String a = y.concat(z);
return a;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
query = new DatabaseQuery(this);
/*If file exists then tables in db created successfully*/
File file = new File("exists.txt");
boolean success = file.exists();
if (success==false) {
try {
ArrayList<Status> statuses = new ArrayList<Status>();
Twitter twitter = new TwitterFactory().getInstance("USERNAME", "PASSWORD");
statuses = twitter.getUserTimeline();
/* adds status data to database*/
for(Status s: statuses){
query.appendData("Text", s.getText());
query.appendData("Date", this.getThisYearDate(s.getCreatedAt()));
query.appendData("ID",String.valueOf(s.getId()) );
query.addRow();
}
}
catch (TwitterException te) {
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit( -1);
}
try{
boolean created = file.createNewFile();
}
catch (IOException e) {
System.out.println("error");
}
queryString = query.getData(new String[] {"Text"},this.getThisYearDate(new Date()), null, null, null, "Date", " ASC");
try {
query.destroy();
} catch (Throwable e) {
e.printStackTrace();
}
} else {
// File already exists
queryString = query.getData(new String[] {"Text"},this.getThisYearDate(new Date()), null, null, null, "Date", " ASC");
try {
query.destroy();
} catch (Throwable e) {
e.printStackTrace();
}
}
// Set the ListView
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, queryString));
getListView().setTextFilterEnabled(true);
}
}