如果我不使用AsyncTask,它运行正常。我这样做是因为它从服务器获取数据并在sqlite数据库中写入。 Iam在标签布局的第一个片段上调用它。
这是第一个片段
public class TabFragment7 extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerInBackground1(); // this method
}
}
registerInBackground1();方法
private void registerInBackground1() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
TabFragment0 tab1= new TabFragment0();
try {
tab1.getRSSfeedstoSqLite(); //this methods fetches data
from server and writes it in sqlite database
} catch (RSSReaderException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}.execute(null, null, null);
}
getRSSfeedstoSqLite() 在此方法中,创建一个sqlite数据库并存储它。 如果你们知道更好的方法,请建议我。
public void getRSSfeedstoSqLite() throws RSSReaderException, IOException {
SQLiteDatabase mydatabase = getActivity().openOrCreateDatabase("aappen", getActivity().MODE_PRIVATE, null);
Log.d(SHETTY, "getRSSfeedstoSqLite: 1 " + mydatabase);
RSSMasterInfo.RssInfoPhp rssInfophp = new RSSMasterInfo.RssInfoPhp();
RSSMasterList = rssInfophp.getData();
rssItems = new ArrayList<RSSItem>();
// RssLinkForOnTouch = new ArrayList<RSSMasterInfo.RssfeedSubCategoryLink>();
for (int j = 0; j < RSSMasterList.size(); j++) {
RSSReader reader = new RSSReader();
String uri = RSSMasterList.get(j).getLink();
RSSFeed feed = reader.load(uri);
Names = RSSMasterList.get(j).getNames();
Urls = RSSMasterList.get(j).getUrls();
Imagelinks = RSSMasterList.get(j).getImageinks();
rssItems = feed.getItems();
for (RSSItem rssItem : rssItems) {
int count = 0;
Log.i("RSS Reader ", rssItem.getTitle());
Uri v = rssItem.getLink();
String Header = rssItem.getTitle().replace("'", "`");
String Details = rssItem.getDescription().replace("'", "`");
String Link = rssItem.getLink().toString();
String PubDatestr = Formats.TIMESTAMP.formatValue(rssItem.getPubDate());
System.out.println("DATE@@@@@@@@@ "+PubDatestr+" "+" URI "+uri+" "+rssItems);
/*
Instance to create the current time values
*/
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+05:30"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
String localTime = date.format(currentLocalTime);
String Randomid = UUID.randomUUID().toString();
String RssSource = rssItem.getLink().toString();
/*
Code to split the rss link got to show the Source as: www.deccanherald.com
*/
String res2 = RssSource.substring(7, RssSource.length());
String finalSplitRssSource = res2.substring(0, res2.indexOf("/"));
String ActualRssSource = finalSplitRssSource.toString();
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS rssdata(ID VARCHAR,header VARCHAR(1000) , detail VARCHAR(8000) , link VARCHAR(2000) , pubdate VARCHAR(100) , rsssource VARCHAR(100) , datetime VARCHAR(50) );");
mydatabase.execSQL("DELETE FROM rssdata WHERE link= '" + Link + "' ");
mydatabase.execSQL("UPDATE rssdata SET datetime= '" + localTime + "' ");
mydatabase.execSQL("INSERT INTO rssdata VALUES('" + Randomid + "' , '" + Header + "' , '" + Details + "' , '" + Link + "' , '" + PubDatestr + "' , '" + ActualRssSource + "' , '" + localTime + "' ) ");
Cursor res1 = mydatabase.rawQuery("select * from rssdata where link= '" + Link + "' ", null);
String RssFeedResults = null;
res1.moveToFirst();
if (res1.getCount() == 1) {
RssFeedResults = res1.getString(0);
}
System.out.println(RssFeedResults);
}
}
}
logcat的
09-15 12:32:18.489 16186-17460/aappen.com.buddiesnew E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.NullPointerException
at aappen.com.buddiesnew.TabFragment0.getRSSfeedstoSqLite(TabFragment0.java:935)
at aappen.com.buddiesnew.TabFragment7$1.doInBackground(TabFragment7.java:81)
at aappen.com.buddiesnew.TabFragment7$1.doInBackground(TabFragment7.java:71)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
指向线下
SQLiteDatabase mydatabase = getActivity().openOrCreateDatabase("aappen", getActivity().MODE_PRIVATE, null);
我用try / catch块捕获了那个空指针异常只是为了检查它是否会继续但此时再次出现空指针异常。 那么伙计们请建议我如何解决这个问题。
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS rssdata(ID VARCHAR,header VARCHAR(1000) , detail VARCHAR(8000) , link VARCHAR(2000) , pubdate VARCHAR(100) , rsssource VARCHAR(100) , datetime VARCHAR(50) );");
答案 0 :(得分:2)
正如我们发现的那样,getActivity()
返回null。这意味着在那一刻片段没有附加到某些Activity
。可能是你的调用在附加之前或者在分离之后发生 - 我认为在分离之后因为同步代码不会抛出异常。
无论如何,有Fragment
生命周期错误。如果这些信息不够,我需要更多的片段类代码。
<强>糟糕强>
第一次没见:)
TabFragment0 tab1= new TabFragment0();
tab1.getRSSfeedstoSqLite();
你根本没有附加片段。因此getActivity()
电话中没有任何价值。使用FragmentManager
将片段添加到某些活动中。
后来添加了解决方案
只需向FragmentManager
添加片段重复解决方案。我不知道你将如何获得参考,因为getFragmentManager()
是Activity
的方法。因此,如果您已经有活动参考,请使用它。最简单的方法是在Fragment
类中创建构造函数,以获得参数作为参数。
openOrCreateDatabase
是Context
的方法。所以没有必要从活动中调用它。您可以获得custom application class的静态字段。
可能最好只是获取之前创建的片段的引用。您可以通过FragmentManager
(再次)的ID或标记获取它。