Android AsyncTask OutOfBoundsException - java

I have an error on my stock quoting application. I have an app where you input your a stock (as in stock market) code and will list it with two buttons. One button to display a quote and the other to view more info from the web. The web function is fine but the app crashes when I hit the quote button.
I think that this is the method in question.
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(args[0]);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("quote");
if(nl != null && nl.getLength() > 0) {
for(int i=0; i < nl.getLength(); i++){
StockInfo theStock = getStockInformation(docEle);
name = theStock.getName();
yearLow = theStock.getYearLow();
yearHigh = theStock.getYearHigh();
daysLow = theStock.getDaysLow();
daysHigh = theStock.getDaysHigh();
lastTradePriceOnly = theStock.getLastTradePriceonly();
change = theStock.getChange();
daysRange = theStock.getDaysRange();
}
}
}
}
catch (MalformedURLException e) {
Log.d(TAG, "MalformedURLException", e);
} catch (IOException e) {
Log.d(TAG, "IOException", e);
} catch (ParserConfigurationException e) {
Log.d(TAG, "Parser Configuration Exception", e);
} catch (SAXException e) {
Log.d(TAG, "SAX Exception", e);
}
finally { }
return null;
}
LogCat is showing that I have an OutOfBoundsException in doInBackground() of my StockInfoActivity class but I can't find it. Will appreciate any help in locating the problem.
10-02 02:59:52.738: E/AndroidRuntime(26553): FATAL EXCEPTION: AsyncTask #4
10-02 02:59:52.738: E/AndroidRuntime(26553): java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 02:59:52.738: E/AndroidRuntime(26553): at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-02 02:59:52.738: E/AndroidRuntime(26553): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.lang.Thread.run(Thread.java:841)
10-02 02:59:52.738: E/AndroidRuntime(26553): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-02 02:59:52.738: E/AndroidRuntime(26553): at com.example.stockquote.StockInfoActivity$MyAsyncTask.doInBackground(StockInfoActivity.java:93)
10-02 02:59:52.738: E/AndroidRuntime(26553): at com.example.stockquote.StockInfoActivity$MyAsyncTask.doInBackground(StockInfoActivity.java:1)
10-02 02:59:52.738: E/AndroidRuntime(26553): at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-02 02:59:52.738: E/AndroidRuntime(26553): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-02 02:59:52.738: E/AndroidRuntime(26553): ... 4 more
Sorry I'm having a tough time isolating the problem.

Related

releaseEncoder MediaMuxer in android 4.1

I have created an application containing image to video maker and i using MediaMuxer to creating video from sequence of images but SlideEncoder add second image to auto close MediaMuxer and application is crush.
05-22 07:58:33.691 6091-6122/com.aspiration.imagetovideomaker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
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:856)
Caused by: java.lang.IllegalStateException
at android.media.MediaCodec.native_configure(Native Method)
at android.media.MediaCodec.configure(MediaCodec.java:257)
at com.aspiration.imagetovideomaker.encoding.SlideEncoder.prepareEncoder(SlideEncoder.java:57)
at com.aspiration.imagetovideomaker.ImageToVideo$EncodingTask.doInBackground(ImageToVideo.java:221)
at com.aspiration.imagetovideomaker.ImageToVideo$EncodingTask.doInBackground(ImageToVideo.java:205)
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:856) 
here my video creation code:
SlideEncoder slideEncoder = new SlideEncoder();
try {
slideEncoder.prepareEncoder(outputFile);
Bitmap prevBm = null;
dialog.setMax(MyApplication.bitmapList.size());
for (int idx = 0; idx < MyApplication.bitmapList.size(); idx++) {
publishProgress(String.valueOf(idx + 1));
SlideShow.init();
if (idx > 0) prevBm = MyApplication.bitmapList.get(idx - 1);
Bitmap curBm = MyApplication.bitmapList.get(idx);
for (int i = 0; i < (MyApplication.FRAME_PER_SEC * MyApplication.SLIDE_TIME); i++) {
// Drain any data from the encoder into the muxer.
slideEncoder.drainEncoder(false);
// Generate a frame and submit it.
slideEncoder.generateFrame(curBm, curBm);
//slideEncoder.generateFrame(prevBm, curBm);
}
}
slideEncoder.drainEncoder(true);
} catch (IOException e) {
e.printStackTrace();
} finally {
slideEncoder.releaseEncoder();
}
here my prepareEncoder
public void prepareEncoder(File outputFile) throws IOException {
mBufferInfo = new MediaCodec.BufferInfo();
try {
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, WIDTH, HEIGHT);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, MyApplication.BIT_RATE);
format.setInteger(MediaFormat.KEY_FRAME_RATE, MyApplication.FRAME_PER_SEC);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
mEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mEncoder.createInputSurface();
mEncoder.start();
mMuxer = new MediaMuxer(outputFile.getPath().toString(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
mTrackIndex = -1;
mMuxerStarted = false;
} catch (Exception e) {
e.printStackTrace();
Log.e("SlideEncoder", e.toString());
}
}

Error occured while executing doInBackground() while running Countdowntimer

I am trying to run a countdowntimer in background to do some computation through asynctask but i am getting this error
This is my code
public class CurrentStatus extends AsyncTask<Context,Void,Context> {
float BatteryStatus;
int TimeStatus,HoursToCharge;
String USID, BatteryID, NetworkID, NetworkStatus, roamingLevel,
TimeID,ETTC,DischargeRate;
int dischargeRate;
Context newContext;
SharedPreferences sharedPreferences;
public float getBatteryLevel(Context context)
{
Intent batteryIntent = context.registerReceiver(null, new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
return ((float) level / (float) scale) * 100.0f;
}
public void getDischargeRate(final Context context)
{
final int currentBattery=(int)getBatteryLevel(context);
int q=0;
sharedPreferences=context.getSharedPreferences
("MyDischargePref" ,Context.MODE_PRIVATE);
final SharedPreferences.Editor editor1=sharedPreferences.edit();
new CountDownTimer(120000,600)
{
int BatteryDischargeRate;
public void onTick(long millisUntilFinished)
{
System.out.println(" seconds"+currentBattery);
}
int afterUsage;
public void onFinish()
{
afterUsage = (int)getBatteryLevel(context);
System.out.println("On Finish: "+ afterUsage);
BatteryDischargeRate=currentBattery-afterUsage;
System.out.println("Entering preference. BYE!
"+BatteryDischargeRate);
editor1.putString("DischargeRate",Integer.toString(BatteryDischargeRate));
}
}.start();
}
public String getNetworkInterface(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled())
return "On";
else
return "Off";
}
public String getRoaming(Context context) {
boolean x = false;
TelephonyManager telephoneManager;
telephoneManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
x = telephoneManager.isNetworkRoaming();
if (x)
return "On";
else
return "Off";
}
public String getDataConnectionType(Context context) {
TelephonyManager telephoneManager;
telephoneManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
int a = telephoneManager.getNetworkType();
switch (a) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_IDEN:
case TelephonyManager.NETWORK_TYPE_EDGE:
String nw = "00";
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
nw = "01";
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE:
nw = "11";
return "4G";
default:
return "Unknown";
}
}
public String getDataMode(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean x = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (x) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return "On";
else
return "Off";
} else
return "No Active Network";
}
public void retrieveStatus(Context context) {
Context retrieveContext=context;
SharedPreferences sharedPreferences=retrieveContext.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
BatteryStatus = getBatteryLevel(retrieveContext);
if (BatteryStatus > 5 && BatteryStatus < 25) {
BatteryID = "11";
}
if (BatteryStatus > 25 && BatteryStatus < 50) {
BatteryID = "10";
}
if (BatteryStatus > 50 && BatteryStatus < 75) {
BatteryID = "01";
}
if (BatteryStatus > 75 && BatteryStatus < 100) {
BatteryID = "00";
}
NetworkID = getNetworkInterface(retrieveContext);
if (NetworkID == "ON") {
NetworkID = getDataConnectionType(retrieveContext);
if (NetworkStatus == "3G") {
NetworkStatus = "11";
}
if (NetworkStatus == "2G") {
NetworkStatus = "10";
}
} else {
NetworkStatus = "00";
}
NetworkID = getNetworkInterface(retrieveContext);
if (NetworkID == "On") {
NetworkStatus = "01";
}
roamingLevel = getRoaming(retrieveContext);
if (roamingLevel.equals("On")) {
roamingLevel = "1";
} else {
roamingLevel = "0";
}
ETTC=(sharedPreferences.getString("ETTC",""));
HoursToCharge=Integer.parseInt(ETTC);
if (HoursToCharge > 12) {
TimeID = "11";
}
if (HoursToCharge > 6 && HoursToCharge < 12) {
TimeID = "10";
}
if (HoursToCharge > 3 && HoursToCharge < 6) {
TimeID = "01";
}
if (HoursToCharge > 0 && HoursToCharge < 3) {
TimeID = "00";
}
DischargeRate=(sharedPreferences.getString("MyDischargePref",""));
System.out.println("Battery id:"+BatteryID);
System.out.println("ETTC:"+TimeID);
System.out.println("Network Status:"+NetworkStatus);
System.out.println("DischargeRate"+DischargeRate);
System.out.println("Roaming"+roamingLevel);
}
#Override
protected Context doInBackground(Context... params) {
Context backgroundcontext;
backgroundcontext=params[0];
getDischargeRate(backgroundcontext);
return backgroundcontext;
}
#Override
protected void onPostExecute(Context context) {
retrieveStatus(context);
}
}
and this is LogCat
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: Process: com.first.shash_000.anantha, PID: 30111
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:304)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.Handler.<init>(Handler.java:200)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.Handler.<init>(Handler.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.CountDownTimer$1.<init>(CountDownTimer.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.CountDownTimer.(CountDownTimer.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus$1.(CurrentStatus.java:55)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus.getDischargeRate(CurrentStatus.java:54)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus.doInBackground(CurrentStatus.java:226)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus.doInBackground(CurrentStatus.java:26)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:292)
You shouldn't put your CountDownTimer inside the doInBackground(), think about changing your code logic to run the timer on the main thread, in onPostExecute(Context context) for example

App has stopped working Android Jsonparser

I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasda‌​sdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}

KitKat Connection from URL get NullPointerException in AsyncTask

i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
             at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}

When emulator begins and try to connect to database, application stops unexpectedly

Hello i'm new to android development and this is my first app. I try to connect to a database but when the emulator starts the application stops unexpectedly. Everything in eclipse is fine but when i run the emulator it stops. Here is the code:
public class Antallaktika extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
String targetname;
String targetsku;
String targetprice;
int responseCode;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.antallaktika);
setTitle("Ανταλλακτικά");
try {
URL url = new URL("http://machina.gr/antallaktika.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
}
catch (Exception e) {}
try{
if(isNetworkAvailable()==true && responseCode == HttpURLConnection.HTTP_OK){
new LoadData().execute();
}
else{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
}
catch(Exception e){
}
}
public class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(Antallaktika.this, ""," Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try{
ListView listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Antallaktika.this,al.toArray(new String[al.size()]),al1.toArray(new String[al1.size()]),al2.toArray(new String[al2.size()])));
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://machina.gr/antallaktika.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
targetname=json_data.getString("targetname");
targetsku=json_data.getString("targetsku");
targetprice = json_data.getString("targetprice");
al.add(targetname);
al1.add(targetsku);
al2.add(targetprice);
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
and the logcat is:
08-01 20:51:36.042: E/AndroidRuntime(375): FATAL EXCEPTION: AsyncTask #1
08-01 20:51:36.042: E/AndroidRuntime(375): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.lang.Thread.run(Thread.java:1019)
08-01 20:51:36.042: E/AndroidRuntime(375): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.Handler.<init>(Handler.java:121)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.widget.Toast.<init>(Toast.java:68)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.widget.Toast.makeText(Toast.java:231)
08-01 20:51:36.042: E/AndroidRuntime(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:161)
08-01 20:51:36.042: E/AndroidRuntime(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:1)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-01 20:51:36.042: E/AndroidRuntime(375): ... 4 more
08-01 20:51:37.142: E/WindowManager(375): Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): android.view.WindowLeaked: Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): at android.view.ViewRoot.<init>(ViewRoot.java:258)
08-01 20:51:37.142: E/WindowManager(375): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-01 20:51:37.142: E/WindowManager(375): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-01 20:51:37.142: E/WindowManager(375): at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-01 20:51:37.142: E/WindowManager(375): at android.app.Dialog.show(Dialog.java:241)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:107)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:90)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:85)
08-01 20:51:37.142: E/WindowManager(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.onPreExecute(Antallaktika.java:85)
08-01 20:51:37.142: E/WindowManager(375): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-01 20:51:37.142: E/WindowManager(375): at com.pythagoras.machina.gr.Antallaktika.onCreate(Antallaktika.java:67)
08-01 20:51:37.142: E/WindowManager(375): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-01 20:51:37.142: E/WindowManager(375): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 20:51:37.142: E/WindowManager(375): at android.os.Looper.loop(Looper.java:130)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 20:51:37.142: E/WindowManager(375): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 20:51:37.142: E/WindowManager(375): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 20:51:37.142: E/WindowManager(375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 20:51:37.142: E/WindowManager(375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 20:51:37.142: E/WindowManager(375): at dalvik.system.NativeStart.main(Native Method)
you are trying to access UI functionality from a thread other than the UI thread (i guess it is the Toast). that is not possible. see here for info on how to run code on the UI thread.

Categories