I am using Jsoup in my Android app to get images from the internet but an getting a NullPointerException.
Java:
public class CollegeInfo extends Activity{
TextView body;
ImageView image1;ImageView image2;ImageView image3;ImageView image4;
ImageView image8;ImageView image7;ImageView image6;ImageView image5;
String college;
String ataglance;
double satHigh;
double satLow;
Bitmap[] bitmap;
String[] imgSrcs;InputStream[] input;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.collegeinfo);
Bundle extras = getIntent().getExtras();
if (extras != null) {
college = extras.getString("tag");
}
SpannableStringBuilder buffer = new SpannableStringBuilder();
body = (TextView) findViewById(R.id.title);
image1 = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2);
image3 = (ImageView) findViewById(R.id.imageView3);
image4 = (ImageView) findViewById(R.id.imageView4);
image5 = (ImageView) findViewById(R.id.imageView5);
image6 = (ImageView) findViewById(R.id.imageView6);
image7 = (ImageView) findViewById(R.id.imageView7);
image8 = (ImageView) findViewById(R.id.imageView8);
try {
Document doc = Jsoup.connect("http://www.forbes.com/colleges/"+college+"/").get();
String name = doc.select("meta[name=keywords]").attr("content");
int nameLen = name.length();
buffer.append(name+"\n");
String city = doc.select("ul[class=address]").select("li").first().text();
buffer.append(city+"\n");
ataglance = "";
for(int i=0;i<8;i++){
ataglance += doc.select("div[class=ataglanz fleft]").select("li").get(i).ownText()+" ";
ataglance += doc.select("div[class=ataglanz fleft]").select("b").get(i).text();
ataglance += "\n";
}
String satRange = doc.select("div[class=ataglanz fleft]").select("b").get(8).text();
int satLength = satRange.length();
try{
satHigh = Double.parseDouble(satRange.substring(satLength-4, satLength));
satLow = Double.parseDouble(satRange.substring(0, satLength-5));
}catch(NumberFormatException e){
e.printStackTrace();
}
satHigh*=1.5; satLow*=1.5;
int satL = (int) Math.round(satLow); int satH = (int) Math.round(satHigh);
ataglance += "SAT Composite Range: "+Integer.toString(satL)+"-"+Integer.toString(satH);
buffer.append(ataglance+"\n");
for(int i = 0;i<8;i++){
Elements img = doc.select("div[id=photos]").select("a");
imgSrcs[i] = img.text();
input[i] = new java.net.URL(imgSrcs[i]).openStream();
bitmap[i] = BitmapFactory.decodeStream(input[i]);
}
image1.setImageBitmap(bitmap[0]);
image2.setImageBitmap(bitmap[1]);
image3.setImageBitmap(bitmap[2]);
image4.setImageBitmap(bitmap[3]);
image5.setImageBitmap(bitmap[4]);
image6.setImageBitmap(bitmap[5]);
image7.setImageBitmap(bitmap[6]);
image8.setImageBitmap(bitmap[7]);
body.setText(buffer.toString());
}catch(IOException e){
e.printStackTrace();
}
}
{
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
}
XML:
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.06" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/imageView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Before I added in the images, everything was working fine, so I believe that I am not parsing the images correctly.
Logcat:
07-29 17:19:49.985: E/AndroidRuntime(10855): FATAL EXCEPTION: main
07-29 17:19:49.985: E/AndroidRuntime(10855): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.collegeselector/com.collegeselector.CollegeInfo}: java.lang.NullPointerException
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.os.Handler.dispatchMessage(Handler.java:99)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.os.Looper.loop(Looper.java:137)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.ActivityThread.main(ActivityThread.java:5039)
07-29 17:19:49.985: E/AndroidRuntime(10855): at java.lang.reflect.Method.invokeNative(Native Method)
07-29 17:19:49.985: E/AndroidRuntime(10855): at java.lang.reflect.Method.invoke(Method.java:511)
07-29 17:19:49.985: E/AndroidRuntime(10855): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-29 17:19:49.985: E/AndroidRuntime(10855): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-29 17:19:49.985: E/AndroidRuntime(10855): at dalvik.system.NativeStart.main(Native Method)
07-29 17:19:49.985: E/AndroidRuntime(10855): Caused by: java.lang.NullPointerException
07-29 17:19:49.985: E/AndroidRuntime(10855): at com.collegeselector.CollegeInfo.onCreate(CollegeInfo.java:87)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.Activity.performCreate(Activity.java:5104)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-29 17:19:49.985: E/AndroidRuntime(10855): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-29 17:19:49.985: E/AndroidRuntime(10855): ... 11 more
What should I change to get the images to work?
Look at your stacktrace:
07-29 17:19:49.985: E/AndroidRuntime(10855): Caused by: java.lang.NullPointerException
07-29 17:19:49.985: E/AndroidRuntime(10855): at com.collegeselector.CollegeInfo.onCreate(CollegeInfo.java:87)
You haven't initialized the string array String[] imgSrcs; yet you try to add content to it in your for each loop:
imgSrcs[i] = img.text();
Also, the size of an array cannot be modified, so you either decide upon a size of it when you initialize it and then stick with it. If you want a dynamic size, use an ArrayList object instead.
Related
I am new on android and trying to develop simple calculator but this Fatal exception : main occurs please help.
I did comment my onClickListner to check but it did'nt helped at all.
package com.example.calculatorsinglescreen;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText value1,value2,myoperator,result;
Button ok;
String strvalue1,strvalue2,stroperator,strresult;
int ivalue1,ivalue2,ioperator,iresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value1 = (EditText) findViewById(R.id.txtvalue1);
value2 = (EditText) findViewById(R.id.txtvalue2);
myoperator = (EditText) findViewById(R.id.txtoperator);
result = (EditText) findViewById(R.id.txtresult);
ok = (Button) findViewById(R.id.btnok);
strvalue1 = value1.getText().toString();
strvalue2 = value2.getText().toString();
stroperator = myoperator.getText().toString();
ivalue1 = Integer.parseInt(strvalue1);
ivalue2 = Integer.parseInt(strvalue2);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (stroperator.equals("+")) {
Toast msg = Toast.makeText(MainActivity.this, "If is running", Toast.LENGTH_LONG);
msg.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my XML file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.calculatorsinglescreen.MainActivity" >
<TextView
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:text="Value 1" />
<TextView
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value1"
android:layout_margin="20dp"
android:text="Value 2" />
<TextView
android:id="#+id/operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value2"
android:layout_margin="20dp"
android:text="Operator" />
<EditText
android:id="#+id/txtvalue1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/value1"
android:layout_alignBaseline="#+id/value1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtoperator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/operator"
android:layout_below="#+id/txtvalue2"
android:layout_toRightOf="#+id/operator"
android:layout_alignParentRight="true"
android:ems="10" />
<EditText
android:id="#+id/txtvalue2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/value2"
android:layout_toRightOf="#+id/value2"
android:layout_below="#+id/txtvalue1"
android:layout_alignParentRight="true"
android:ems="10" />
<Button
android:id="#+id/btnok"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Ok" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/btnok"
android:layout_margin="40dp"
android:text="Result" />
<EditText
android:id="#+id/txtresult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/result"
android:layout_toRightOf="#+id/result"
android:ems="10" />
Here is my LogCat to get a clearer view :
10-18 17:51:25.468: D/AndroidRuntime(742): Shutting down VM
10-18 17:51:25.468: W/dalvikvm(742): threadid=1: thread exiting with uncaught exception (group=0x40015560)
10-18 17:51:25.488: E/AndroidRuntime(742): FATAL EXCEPTION: main
10-18 17:51:25.488: E/AndroidRuntime(742): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calculatorsinglescreen/com.example.calculatorsinglescreen.MainActivity}: java.lang.NumberFormatException: unable to parse '' as integer
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.os.Looper.loop(Looper.java:123)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.reflect.Method.invoke(Method.java:507)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-18 17:51:25.488: E/AndroidRuntime(742): at dalvik.system.NativeStart.main(Native Method)
10-18 17:51:25.488: E/AndroidRuntime(742): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.Integer.parseInt(Integer.java:362)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.Integer.parseInt(Integer.java:332)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.example.calculatorsinglescreen.MainActivity.onCreate(MainActivity.java:34)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-18 17:51:25.488: E/AndroidRuntime(742): ... 11 more
this is the error
java.lang.ClassCastException: android.widget.TextView
check your line 24 and see if you cast the right widget in java -(xml), this error means incompatible cast widget lol...
if everything seems correct-(mean widgets are cast in java to with their respective class) then clean rebuild and restart..
EDIT: It worked.. you've solved it but there is a new error which is
java.lang.NumberFormatException:
its because of this on these lines
ivalue1 = Integer.parseInt(strvalue1);
ivalue2 = Integer.parseInt(strvalue2);
ioperator = Integer.parseInt(stroperator);
so change these to this
Integer.valueOf(strvalue1); do that as follows
and also looking at your codes.. your string values are pullled from the edittext during oncreate which means when the app starts in oncreate before the Onresume(which is called when the app shows on the), and during oncreate the user cant flirt with your app, and going further to input values, so at the end your strings are empty when you pull from the edittext, so basically what im saying is remove these lines
strvalue1 = value1.getText().toString();
and put them in the click events ... i am lucid enough to you??..
EDIT2: OVERALL CODE
for button click
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
strvalue1 = value1.getText().toString();
strvalue2 = value2.getText().toString();
stroperator = myoperator.getText().toString();
ivalue1 = Integer.valueOf(strvalue1);
ivalue2 = Integer.valueOf(strvalue2);
if (stroperator.equals("+")) {
Toast.makeText(MainActivity.this, "If is running", Toast.LENGTH_LONG).show();
}
}
});
remove ioperator = Integer.parseInt(stroperator); from the code.I think Your trying to convert the operator to Integer.
ioperator = Integer.parseInt(stroperator);
if you mean operator like this +,-,/,* , you only can convert to thr char or stay in string and do something like this:
private int plus(int ivalue1 , int ivalue2 , String operator ){
if(operator.equal("+")){
return ivalue1 + ivalue2;
}
return 0;
}
I am using this library https://github.com/chrisbanes/Android-PullToRefresh for implementing a refreshable grid view and i am getting this error:
android.view.InflateException: Binary XML file line #8: Error inflating class com.handmark.pulltorefresh.library.PullToRefreshGridView
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.retrievetweets.FragmentPhotos.onCreateView(FragmentPhotos.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:238)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 24 more
Caused by: java.lang.NullPointerException
at com.handmark.pulltorefresh.library.internal.IndicatorLayout.<init>(IndicatorLayout.java:66)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.addIndicatorViews(PullToRefreshAdapterViewBase.java:355)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.updateUIForMode(PullToRefreshAdapterViewBase.java:328)
at com.handmark.pulltorefresh.library.PullToRefreshBase.init(PullToRefreshBase.java:1142)
at com.handmark.pulltorefresh.library.PullToRefreshBase.<init>(PullToRefreshBase.java:113)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.<init>(PullToRefreshAdapterViewBase.java:74)
at com.handmark.pulltorefresh.library.PullToRefreshGridView.<init>(PullToRefreshGridView.java:35)
... 27 more
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- The PullToRefreshGridView replaces a standard GridView widget. -->
<com.handmark.pulltorefresh.library.PullToRefreshGridView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:id="#+id/pull_refresh_grid"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="0dp"
android:horizontalSpacing="1dp"
android:columnWidth="80dp"
android:stretchMode="columnWidth"
android:gravity="fill"
ptr:ptrMode="both"
ptr:ptrDrawable="#drawable/default_ptr_rotate"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminateOnly="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
And here is the java code for the method onCreateView in FragmentPhotos (the line 55 is this one "ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,"):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ref = "";
fa = getActivity();
ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,
container, false);
bar = (ProgressBar) ll.findViewById(R.id.progressBar);
mPullRefreshGridView = (PullToRefreshGridView) ll
.findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener<GridView>() {
#Override
public void onRefresh(
PullToRefreshBase<GridView> refreshView) {
// TODO Auto-generated method stub
if (NetworkReceiver.mobileConnected) {
new GetDataTaskWhitoutLoading().execute();
} else {
Toast.makeText(
getActivity(),
"Ahora mismo no se pueden cargar nuevos datos."
+ " Comprueba la conexi—n a Internet.",
Toast.LENGTH_LONG).show();
mPullRefreshGridView.onRefreshComplete();
}
}
});
mGridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Do something in response to the click
Intent intent = new Intent(fa, ImageSelected.class);
intent.putExtra("URL_image", mListItems.get(position)
.subSequence(0, mListItems.get(position).length() - 6));
startActivity(intent);
}
});
mListItems = new ArrayList<String>();
mAdapter = new FotosItemAdapter(fa, R.layout.image_group, mListItems);
mGridView.setAdapter(mAdapter);
if (NetworkReceiver.mobileConnected) {
GetDataTask.newInstance(bar).execute();
}
return ll;
}
Thank you!!
Are you importing in your classhpath on eclipse?
Pull to refhresh is a lib for android,then import like this:
project properties> android> add lib.
In my case it solved by adding this to my project.properties :
target=android-19
android.library.reference.1=../library
that library is the name of the handmark library.
hope be useful.
So im parsing JSON data from a API Enabled website, It requires authentiucation by a APIKEY, My issue is that im trying to parse the data then insert it into TextViews on the UI. My current code previously used to use a HashMap and a ListView However now im trying to change it to just populate the data into the TextViews. Currently, I've started changing the code over and now im getting RunTimeExceptions with my current code. Any Help would be greatly appreciated.
Issue Resolved
public class ParseMoreDetails extends Activity {
private Context context;
private static String url = "https://api.company.com/api/systems?";
private static final String TAG_SYSTEM = "systems";
private static final String TAG_SYSTEM_ID = "system_id";
private static final String TAG_CITY = "city";
private static final String TAG_STATE = "state";
private static final String TAG_SYSTEM_NAME = "system_name";
private static final String TAG_SYSTEM_PUBLIC_NAME = "system_public_name";
private static final String TAG_STATUS = "status";
TextView textView;
TextView textView2;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView2);
textView2 = (TextView) findViewById(R.id.TextView01);
textView3 = (TextView) findViewById(R.id.TextView03);
new ProgressTask(ParseMoreDetails.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, ArrayList<String>> {
private ProgressDialog dialog;
ArrayList<String> arrfortextviews;
private ParseMoreDetails activity;
// private List<Message> messages;
public ProgressTask(ParseMoreDetails parseMoreDetails) {
this.activity = parseMoreDetails;
context = parseMoreDetails;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(ArrayList<String> success) {
if(arrfortextviews.size() >0){
textView.setText(success.get(0));
textView2.setText(success.get(1));
textView3.setText(success.get(2));
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected ArrayList<String> doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
arrfortextviews=new ArrayList<String>();
// Using APIKEY from strings.xml
String apikey = getString(R.string.apikey);
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vcolor = c.getString(TAG_SYSTEM_ID);
String vfuel = c.getString(TAG_CITY);
String vtread = c.getString(TAG_STATE);
arrfortextviews.add(vcolor);
arrfortextviews.add(vfuel);
arrfortextviews.add(vtread);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return arrfortextviews;
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="System ID: " />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City:" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="State:" />
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>
</FrameLayout>
</LinearLayout>
Current Errors
RuntimeException - NullPointerException
Leaked Window com.android.internal.policy.impl.PhoneWindow$DecorView
LogCat - UPDATED
05-01 10:27:47.040: E/AndroidRuntime(28236): FATAL EXCEPTION: AsyncTask #1
05-01 10:27:47.040: E/AndroidRuntime(28236): java.lang.RuntimeException: An error occured while executing doInBackground()
05-01 10:27:47.040: E/AndroidRuntime(28236): at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-01 10:27:47.040: E/AndroidRuntime(28236): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.lang.Thread.run(Thread.java:856)
05-01 10:27:47.040: E/AndroidRuntime(28236): Caused by: java.lang.NullPointerException
05-01 10:27:47.040: E/AndroidRuntime(28236): at com.jitesh.androidjsonparser.ParseMoreDetails$ProgressTask.doInBackground(ParseMoreDetails.java:116)
05-01 10:27:47.040: E/AndroidRuntime(28236): at com.jitesh.androidjsonparser.ParseMoreDetails$ProgressTask.doInBackground(ParseMoreDetails.java:1)
05-01 10:27:47.040: E/AndroidRuntime(28236): at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-01 10:27:47.040: E/AndroidRuntime(28236): ... 5 more
05-01 10:27:55.035: I/Choreographer(28236): Skipped 464 frames! The application may be doing too much work on its main thread.
05-01 10:27:55.210: E/WindowManager(28236): Activity com.jitesh.androidjsonparser.ParseMoreDetails has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4285c818 that was originally added here
05-01 10:27:55.210: E/WindowManager(28236): android.view.WindowLeaked: Activity com.jitesh.androidjsonparser.ParseMoreDetails has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4285c818 that was originally added here
05-01 10:27:55.210: E/WindowManager(28236): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:402)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.Window$LocalWindowManager.addView(Window.java:554)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.Dialog.show(Dialog.java:277)
05-01 10:27:55.210: E/WindowManager(28236): at com.jitesh.androidjsonparser.ParseMoreDetails$ProgressTask.onPreExecute(ParseMoreDetails.java:86)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.AsyncTask.execute(AsyncTask.java:534)
05-01 10:27:55.210: E/WindowManager(28236): at com.jitesh.androidjsonparser.ParseMoreDetails.onCreate(ParseMoreDetails.java:63)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.Activity.performCreate(Activity.java:5206)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.access$600(ActivityThread.java:140)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.Looper.loop(Looper.java:137)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.main(ActivityThread.java:4898)
05-01 10:27:55.210: E/WindowManager(28236): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 10:27:55.210: E/WindowManager(28236): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 10:27:55.210: E/WindowManager(28236): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
05-01 10:27:55.210: E/WindowManager(28236): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
05-01 10:27:55.210: E/WindowManager(28236): at dalvik.system.NativeStart.main(Native Method)
In Here :
TextView textView = (TextView) findViewById(R.id.textView2); //<<< here
TextView textView2 = (TextView) findViewById(R.id.TextView01);//<<< here
TextView textView3 = (TextView) findViewById(R.id.TextView03);//<<< here
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
you are using findViewById before setting layout for current Activity .so you will need to move all Widgets initialize inside onCreate method of Activity after setting layout for it. Change your code as:
TextView textView,textView2,textView3; //<<<declare here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize all textViews here
textView = (TextView) findViewById(R.id.textView2);
textView2 = (TextView) findViewById(R.id.TextView01);
textView3 = (TextView) findViewById(R.id.TextView03);
......
you are having an error in doInBackround of the AsyncTask
I suspect that
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);
returns null
put this line instead may be it will work
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url + "key=" + apikey);
you shouldn't handle UI elements (TextViews) from doInBackground OnPostExecute is made for that
public class screen2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
final Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//AInteger.parseInt(string)
System.out.println("1");
EditText et = (EditText)findViewById(R.id.editText1);
System.out.println("2");
int zipCode = Integer.parseInt(et.getText().toString());
System.out.println("3");
System.out.println(zipCode);
System.out.println("dude...5");
}
});
}
}
This code shows the errror in the logcat :
11-13 19:58:06.806: W/KeyCharacterMap(281): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
11-13 19:58:09.471: I/System.out(281): 1
11-13 19:58:09.471: I/System.out(281): 2
11-13 19:58:09.477: D/AndroidRuntime(281): Shutting down VM
11-13 19:58:09.477: W/dalvikvm(281): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-13 19:58:09.527: E/AndroidRuntime(281): FATAL EXCEPTION: main
11-13 19:58:09.527: E/AndroidRuntime(281): java.lang.NullPointerException
11-13 19:58:09.527: E/AndroidRuntime(281): at com.example.andtwi.screen2$1.onClick(screen2.java:23)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.view.View.performClick(View.java:2408)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.view.View$PerformClick.run(View.java:8816)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.os.Handler.handleCallback(Handler.java:587)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.os.Handler.dispatchMessage(Handler.java:92)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.os.Looper.loop(Looper.java:123)
11-13 19:58:09.527: E/AndroidRuntime(281): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-13 19:58:09.527: E/AndroidRuntime(281): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:58:09.527: E/AndroidRuntime(281): at java.lang.reflect.Method.invoke(Method.java:521)
11-13 19:58:09.527: E/AndroidRuntime(281): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-13 19:58:09.527: E/AndroidRuntime(281): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-13 19:58:09.527: E/AndroidRuntime(281): at dalvik.system.NativeStart.main(Native Method)
Though it looks like an Null Pointer exception , i think i am doing it things exactly i found on forums. Here is code of my related xml file as well. Can anyone suggest where am i doing it wrong?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Zipcode" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="5" >
<requestFocus />
</EditText>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get movies from Flixster" />
</LinearLayout>
The code breaks at this as well :
int zipCode = Integer.parseInt(et.getText().toString());
Try this:
Button button1 = (Button)findViewById(R.id.button1);
EditText et = (EditText)findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("1");
System.out.println("2");
String zipCode = et.getText().toString();
System.out.println("3");
System.out.println(zipCode);
}
}
I think,you don't need to write String zipCode = (String)et.getText().toString(); there as it is already returns a String object.
And hope,you don't miss to include setContentView(R.layout.your_xml_file); before declaring a Button and EditText.
Edit 1:
You don't seem to get problem with
int zipCode=Integer.parseInt(et.getText().toString()); there.Try this with above code modification.
You might be getting null pointer exception because you are getting String s=et.getText().toString() as null.Please check it for null before casting it to int.
Button button1 = (Button)findViewById(R.id.button1);
EditText et = (EditText)findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("1");
System.out.println("2");
String check = et.getText().toString();
int zipCode=0;
if(!check.equals(""))
zipCode=Integer.parseInt(check);
System.out.println("3");
System.out.println(zipCode);
}
}
Could you post your onCreate method, as well as line 23 on its own? The most likely problem is that you neglect to call setContentView and that is why findViewById returns null.
for some reason, I am getting a ClassCastException error. I don't really know why.
Thanks in advance, I am a new programmer and any help would really help (no pun intended).
Code:
final EditText answerBox = (EditText) findViewById(R.id.answerBox);
final Button button = (Button) findViewById(R.id.button);
final TextView problem = (TextView) findViewById(R.id.problem);
final TextView status = (TextView) findViewById(R.id.status);
final TextView num = (TextView) findViewById(R.id.numerator);
final TextView denom = (TextView) findViewById(R.id.denominator);
button.setOnClickListener(new OnClickListener()
{
private String inputString;
public void onClick(View v)
{
inputString = problem.getText().toString();
int firstNumber = Integer.parseInt(inputString.substring(0,1));
int secondNumber = Integer.parseInt(inputString.substring(2,3));
int correct = firstNumber + secondNumber;
int input;
if(!answerBox.getText().toString().equals(""))
input = Integer.parseInt(answerBox.getText().toString());
else
input = -1;
if(input != -1)
{
if(input == correct)
{
status.setText("Nice! You are correct!");
denom.setText(Integer.parseInt(denom.getText().toString()) +1);
num.setText(Integer.parseInt(num.getText().toString()) +1);
}
else
{
status.setText("Sorry, but your answer was wrong.");
denom.setText(Integer.parseInt(denom.getText().toString()) +1);
}
}
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
String newProblem = Integer.toString(a) + "+" + Integer.toString(b);
problem.setText(newProblem.toString());
answerBox.setText("");
}
});
Once again, thanks.
Stuff from LogCat:
10-30 04:04:10.490: ERROR/AndroidRuntime(551): FATAL EXCEPTION: main
10-30 04:04:10.490: ERROR/AndroidRuntime(551): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.benhsu.Addition/com.benhsu.Addition.AdditionActivity}: java.lang.ClassCastException: android.widget.TextView
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.os.Looper.loop(Looper.java:123)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at java.lang.reflect.Method.invoke(Method.java:507)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at dalvik.system.NativeStart.main(Native Method)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): Caused by: java.lang.ClassCastException: android.widget.TextView
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at com.benhsu.Addition.AdditionActivity.onCreate(AdditionActivity.java:24)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-30 04:04:10.490: ERROR/AndroidRuntime(551): ... 11 more
XML Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:id="#+id/problem" android:layout_height="wrap_content" android:text="#string/problemString"/>
<EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="#+id/answerBox">
<requestFocus></requestFocus>
</EditText>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/status" android:id="#+id/status"></TextView>
<Button android:text="Button" android:layout_height="wrap_content" android:id="#+id/button" android:layout_width="wrap_content"></Button>
<RelativeLayout android:id="#+id/relativeLayout1" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.14">
<TextView android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_height="wrap_content" android:layout_alignBottom="#+id/textView1" android:text="#string/score" android:id="#+id/textView2" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_alignBaseline="#+id/textView1"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/numerator" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_alignParentTop="true" android:layout_toRightOf="#+id/textView2" android:layout_marginLeft="18dp" android:text="#string/numerator"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="#string/fraction" android:id="#+id/fraction" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_alignParentTop="true" android:layout_toRightOf="#+id/numerator" android:layout_marginLeft="14dp"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="#string/denominator" android:id="#+id/denominator" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_alignParentTop="true" android:layout_toRightOf="#+id/fraction" android:layout_marginLeft="19dp"></TextView>
</RelativeLayout>
</LinearLayout>
EDIT
It worked fine for me. In Eclipse, go to Project->Clean... and try again. It could be that your R file is out of sync.