null pointer exception in AQuery (Android query) function - android

In my code I used AQUery library to load image from web but it is showing null pointer exception at "aq.id(R.id.img);" in my code ...in class i created globle object of AQuery class and i define function inside inner class methode.....null pointer exception at "aq.id(R.id.img)" which is inside getview methode of cusomgrid class..
public class Customgrid extends Activity {
public int gotbread;
public int get, send;
AQuery aq;
String url1[] = { "https://www.dropbox.com/s/f308a9s5ycuc3mh/1.jpg",
"https://dl.dropbox.com/s/2s60g4e696566nt/2.jpg",
"https://dl.dropbox.com/s/59t6wo83ekzff0y/3.jpg",
"https://dl.dropbox.com/s/1b58qtj4ftm87yc/4.jpg",
"https://dl.dropbox.com/s/py7ogwstc0814zg/5.jpg",
"https://dl.dropbox.com/s/ocavtv1tkr6wtvv/6.jpg" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.customgview);
AQuery aq = new AQuery(Customgrid.this);
// Bundle gotbasket = getIntent().getExtras();
// gotbread = gotbasket.getInt("pos");
gotbread = getIntent().getExtras().getInt("position");
get = gotbread;
GridView grdview = (GridView) findViewById(R.id.gridView);
grdview.setAdapter(new Customgridadapter(this));
grdview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Bundle basket = new Bundle();
basket.putInt("position", send);
Intent i = new Intent(Customgrid.this,
FullScreenImageActivity.class);
i.putExtras(basket);
startActivity(i);
}
});
grdview.setVerticalSpacing(0);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
public class Customgridadapter extends BaseAdapter {
public Integer[] images1 = { R.drawable.s_1, R.drawable.s_2,
R.drawable.s_3 };
public Integer[] images2 = { R.drawable.s_5, R.drawable.s_6,
R.drawable.s_4 };
Context m1Context;
public Customgridadapter(Context context) {
super();
this.m1Context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return images1.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
int pos = 0;
LayoutInflater inflater = ((Activity) m1Context)
.getLayoutInflater();
View customRow1 = inflater.inflate(R.layout.gview, null);
ImageView image = (ImageView) customRow1
.findViewById(R.id.imageforgrid);
aq.id(R.id.imageforgrid);
aq.image(url1[0],true,true);
Bitmap bm = DownloadImage(url1[0]);
switch (gotbread) {
case 0:
image.setImageBitmap(bm);
break;
case 1:
image.setImageBitmap(bm);
break;
}
image.setAdjustViewBounds(true);
image.setScaleX((float) 0.9);
image.setScaleY((float) 0.9);
switch (get) {
case 0:
send = get + position;
break;
case 1:
send = 10 * 1 + position;
break;
case 2:
send = 10 * 2 + position;
break;
case 3:
send = 10 * 3 + position;
break;
case 4:
send = 10 * 4 + position;
break;
}
// image.setOnClickListener(new OnImageClickListener(position));
return customRow1;
}
}

You have
AQuery aq = new AQuery(Customgrid.this); // declared and initialized in oncreate
in onCreate becomes local to onCreate.
Change to
aq = new AQuery(Customgrid.this);
The instance variable aq was never initialized giving NPE.
public class Customgrid extends Activity {
public int gotbread;
public int get, send;
AQuery aq; // not initialized
Also no network related operation on the ui thread.

Related

second fragment run in first fragment and third in second

My requierment is when I click the button in firstfragment load meaning from database ,then screen move to next screen (swipe to secondfragment) automaticaly image load from given url and display in image, then swipe to thirdfragment automatically audio load from given url, and same task for video.
Given code imagefragment(second fragment) load in meaningfragment(first fragment) and third in second, and fourth in third.
***Meaning fragment( First Fragment)***
String url2 = "";
String webdata = "";
int wifi = 0;
int first = 1;
View view;
List<String> wordslist;
ImageButton find;
EditText word;
WebView data;
TextView urdu_meaning;
ListView lv;
SqlLiteDbHelper dbHelper;
GetMeaning urdu ;
NetworkInfo mWifi;
ConnectivityManager connManager;
WifiManager wifiManager;
public static String urlword = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
view = inflater.inflate(R.layout.meaningview, container, false);
word = (EditText) view.findViewById(R.id.word);
find = (ImageButton) view.findViewById(R.id.find);
data = (WebView) view.findViewById(R.id.web);
urdu_meaning = (TextView) view.findViewById(R.id.Urdu_Text);
lv = (ListView) view.findViewById(R.id.listofword);
Typeface tf= Typeface.createFromAsset(getActivity().getAssets(), "jameel.ttf");
urdu_meaning.setTypeface(tf);
if(first == 1)
{
try {
dbHelper = new SqlLiteDbHelper(getActivity());
dbHelper.CopyDataBaseFromAsset();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
first++;
}
word.addTextChangedListener(new TextWatcher() {
#SuppressWarnings("static-access")
#SuppressLint("InlinedApi")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if (!word.getText().toString().equalsIgnoreCase(""))
{
wordslist = dbHelper.Loadwords(word.getText().toString());
//wordslist.toString()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_selectable_list_item, wordslist);
lv.setVisibility(view.VISIBLE);
lv.setAdapter(adapter);
data.setVisibility(view.INVISIBLE);
urdu_meaning.setVisibility(view.INVISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("static-access")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
word.setText(wordslist.get(position));
lv.setVisibility(view.INVISIBLE);
}
});
find.setOnClickListener(new OnClickListener() {
#SuppressWarnings("static-access")
#SuppressLint({ "NewApi", "DefaultLocale" })
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
lv.setVisibility(view.INVISIBLE);
data.setVisibility(view.VISIBLE);
urdu_meaning.setVisibility(view.VISIBLE);
url2 = word.getText().toString().toLowerCase();
AudioFragment.audioclick = 0;
VideoFragment.videoclick = 0;
ImageFragment.imageclick = 0;
urlword = url2;
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if(url2.isEmpty())
{
Toast.makeText(getActivity(), "Word is missing! ", Toast.LENGTH_LONG).show();
}
else
{
try{
urdu = dbHelper.getDetail(word.getText().toString());
urdu_meaning.setText(urdu.Meaning.toString());
}catch(Exception e){
e.printStackTrace();
urdu_meaning.setText("Urdu word not found");
}
if (mWifi.isConnected())
{
data.loadUrl(url1 + url2);
}
else
{
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
//wifiManager.setWifiEnabled(true);
}
}
}
});
return view;
}
***Image Fragment Second Fragment***
if(imageclick == 0)
{
//imageURL1 = imageURL + MeaningFragment.urlword + ".jpg";
word.setVisibility(View.INVISIBLE);
// Execute the task
//GetXMLTask task = new GetXMLTask();
//task.execute(imageURL1);
// Create an object for subclass of AsyncTask
}
find.setOnClickListener(new OnClickListener() {
#SuppressWarnings("static-access")
#SuppressLint({ "NewApi", "DefaultLocale" }) #Override
public void onClick(View v) {
if(imageclick == 0)
{
imageURL2 = MeaningFragment.urlword.toString().toLowerCase();
word.setVisibility(View.VISIBLE);
word.setText(MeaningFragment.urlword.toString().toLowerCase());
prevword.setVisibility(View.INVISIBLE);
}
else
{
word.setVisibility(View.VISIBLE);
prevword.setVisibility(View.INVISIBLE);
imageURL2 = word.getText().toString().toLowerCase();
}
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if(imageURL2.isEmpty())
{
Toast.makeText(getActivity(), "Word is missing! ", Toast.LENGTH_LONG).show();
imageView.setVisibility(View.INVISIBLE);
}
else
{
imageURL2 = imageURL2 + ".jpg";
imageURL1 = (imageURL + imageURL2);
//searchurdu();
if(mWifi.isConnected())
{
try{
// Execute the task
GetXMLTask task = new GetXMLTask();
task.execute(imageURL1);
// Create an object for subclass of AsyncTask
}catch(Exception e){
e.printStackTrace();
}
//task.execute("http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png");
// TODO Auto-generated method stub
}
else
{
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
//wifiManager.setWifiEnabled(true);
}
}
}
});
return view;
}
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try{
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}return map;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//pDialog.show();
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
imageView.setVisibility(View.VISIBLE);
pDialog.dismiss();
if(result == null){
Toast.makeText(getActivity(), "Image Not Found", Toast.LENGTH_LONG).show();
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
try {Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
return bitmap;
} catch (IOException e1) {
e1.printStackTrace();
return null;
}
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
try {InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}return stream;
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getActivity(), " Word not Found", Toast.LENGTH_LONG).show();
return null;
}
and same method for audio and video.....

Downloading Image from URL

I got a List View in my application in which I am displaying the data through Base Adapter. Their is two problems I am facing and referred few posts like but all suggested same procedure i followed.
Issues are
I am trying to download the image from the URL given from JSON. everything is working smoothly but the image never get set to Image View.
I bound Text to Speech on click event of button in Base Adapter class and freed it in onDestroy of of the java class but still I get a error in Log for it stating this and application crashes. Here in log erroe line no 55 is the first statement of onDestroy.
Here is my code
Java File
public class DisplayWeather extends Activity {
String city, date, maximumTemp, minimumTemp, description, weatherImageUrl;
ListView weatherList;
List <Bean> bean;
Bitmap myBitmap, newBitmap;
CustomBaseAdapter baseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_weather);
bean = new ArrayList<Bean>();
weatherList = (ListView) findViewById(R.id.lvWeather);
for(int i=0; i<WeatherHome.arrayList.size(); i++)
{
.
.
}
weatherList.setAdapter(new CustomBaseAdapter(this, bean));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (baseAdapter.tts != null)
{
baseAdapter.tts.stop();
baseAdapter.tts.shutdown();
}
super.onDestroy();
}
Base Adapter class
public class CustomBaseAdapter extends BaseAdapter implements OnInitListener {
Context context;
List<Bean> bean;
ImageView weatherImage;
TextView weatherDate, weatherCity, weatherMinimum, weatherMaximum, weatherDescription;
Button buttonSpeak;
String citySpeak, dateSpeak, descriptionSpeak, maximumSpeak, minimumSpeak, weatherURL;
TextToSpeech tts;
Bean userBean;
Bitmap myBitmap;
public CustomBaseAdapter(Context context, List<Bean> bean) {
// TODO Auto-generated constructor stub
this.context = context;
this.bean = bean;
tts = new TextToSpeech(context, null);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return bean.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return bean.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return bean.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
convertView = inflater.inflate(R.layout.custom_base_adapter, null);
weatherImage = (ImageView) convertView.findViewById(R.id.displayImage);
convertView.findViewById(R.id.displayDate);
buttonSpeak = (Button) convertView.findViewById(R.id.Speak);
}
weatherURL = userBean.getImageUrl();
new ImageDownload().execute();
Log.i("Executing Rest Line>>>", "Skippedddddd");
buttonSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String cityName = weatherCity.getText().toString();
String dateValue = weatherDate.getText().toString();
String maximumValue = weatherMaximum.getText().toString();
String minimumValue = weatherMinimum.getText().toString();
String descriptionValue = weatherDescription.getText().toString();
citySpeak = "Temprature for city "+cityName+"";
dateSpeak = " on Date "+dateValue+"";
maximumSpeak = "will be Maximum upto "+maximumValue+" degree ";
minimumSpeak = " and Minimum upto"+minimumValue+" degree ";
descriptionSpeak = "and The atmosphere seems to be "+descriptionValue+"";
speakTempratureValues();
}
});
return convertView;
}
private class ImageDownload extends AsyncTask<String, Void, Bitmap>{
protected Bitmap doInBackground(String... arg0){
try{
Log.e("src",weatherURL);
URL url = new URL(weatherURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Bitmap result){
if(result!=null)
{
Log.i("OnPost>>>", ""+result);
weatherImage.setImageBitmap(result);
}
}
}
protected void speakTempratureValues() {
// TODO Auto-generated method stub
tts.setSpeechRate(-4);
tts.speak(citySpeak, TextToSpeech.QUEUE_FLUSH, null);
tts.speak(dateSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak(maximumSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak(minimumSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak(descriptionSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak("Thank You", TextToSpeech.QUEUE_ADD, null);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status==TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
else{
speakTempratureValues();
}
}
else{
Log.e("TTS", "Initialization Failed");
}
}
}
It looks like maybe you're returning your convertView in the getView method before your AsyncTask is finished downloading the image. Can you use a thread instead, and use the Thread join method so that your app waits for the image to be downloaded? For an AsyncTask you usually use a progress dialog until the task is finished, but I don't think you can do that inside of an adapter.
How about replacing this:
new ImageDownload().execute();
with this:
new Thread(new Runnable() {
public void run() {
try{
Log.e("src",weatherURL);
URL url = new URL(weatherURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
}
catch(Exception e){
e.printStackTrace();
return null;
}}
}).join();
and then obviously get rid of the ImageDownload class. I'm just throwing this at you, didn't test it or anything. I think that should get you closer.
What Louis suggested is the correct way. I am sure this will work. The reason why it's not working for you is not sure but try this way:
Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try{
Log.e("src",weatherURL);
URL url = new URL(weatherURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned"+myBitmap);
if(myBitmap!=null)
{
Log.i("OnPost>>>", ""+myBitmap);
weatherImage.setImageBitmap(myBitmap);
}
}
catch(Exception e){
e.printStackTrace();
}
}
};
Thread t = new Thread(runnable);
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Probably, the start method was missing for you and you might not have called it.
I hope this work.

Activity indicator in android

In my application i am loading data in a galleryview.If user clicks any item in galleryview i will load data from adapterclass.I kept an activity indicator between this loading and displaying data.But the activity indicator is not dismissing,it is showing continuously.
My activity code:
gal.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick (AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
// mDialog = new ProgressDialog(NewsPaperNov28MainGalleryActivity.this);
// mDialog.setMessage("Please wait...");
// mDialog.setCancelable(false);
mDialog= ProgressDialog.show(NewsPaperNov28MainGalleryActivity.this,"Working..", "Please Wait", true,false);
context.getInstance().setAppVariable("sectionurl", adapter.sectionurl[position]);
Thread thread = new Thread();
thread.start();
// ListView list=(ListView)findViewById(R.id.list);
// listadapter = new ListViewwithimageAdapter(this);
// list.setAdapter(listadapter);
}
});
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// TODO Auto-generated method stub
context.getInstance().setAppVariable("storyurl", listadapter.url[position]);
Intent in = new Intent(getApplicationContext(), NewsDescription.class);
startActivity(in);
}
});
}
#Override
public void run() {
// TODO Auto-generated method stub
// context.getInstance().setAppVariable("sectionurl", adapter.sectionurl[position]);
System.out.println("inside run");
list=(ListView)findViewById(R.id.list);
listadapter = new ListViewwithimageAdapter(this);
System.out.println("B4 handle");
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
System.out.println("Inside handler");
mDialog.dismiss();
list.setAdapter(listadapter);
}
};
My ListViewwithimageAdapter class:
public class ListViewwithimageAdapter extends BaseAdapter
{
private static Context contxt;
final String URL = "http://xxxxxxx/xml/stories/"+rgd.xml;
String[] kickerimage = {};//new String[50];
ListViewwithimageAdapter(Context conxt)
{
this.contxt=conxt;
getelement();
}
public ListViewwithimageAdapter(
OnItemSelectedListener onItemSelectedListener)
{
// TODO Auto-generated constructor stub
// this.contxt=conxt;
getelement();
}
public ListViewwithimageAdapter(OnItemClickListener onItemClickListener) {
// TODO Auto-generated constructor stub
getelement();
}
String[] itemsarray = {};//new String[100];
String[] url= {};//new String[30];
public String[] getelement()
{
// System.out.println("Insid getelement");
ArrayList<String> menuItems = new ArrayList<String>();
TaplistingParser parser = new TaplistingParser();
// System.out.println("url="+URL);
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
// System.out.println("sssss="+doc);
NodeList nl=doc.getElementsByTagName("article");
kickerimage = new String[nl.getLength()];
url = new String[nl.getLength()];
// String headings = null;
for(int i=0; i < nl.getLength(); i++)
{
// System.out.println("i="+i);
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// map.put("Title", parser.getValue(e, "title"));
// map.put("Date", parser.getValue(e, "create_date"));
url[i]=parser.getValue(e, "url");
// System.out.println("b4 kick");
// System.out.println("value="+parser.getValue(e, "title"));
kickerimage[i]=parser.getValue(e, "kickerimage");
// System.out.println("after kick");
// System.out.println("kick="+kickerimage[i]);
menuItems.add(parser.getValue(e, "title"));
}
// System.out.println("b4 items array");
itemsarray = new String[menuItems.size()];
// System.out.println("subbu");
itemsarray=menuItems.toArray(itemsarray);
// System.out.println("subbu1");
// System.out.println("in last");
return itemsarray;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return itemsarray.length;
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return itemsarray[position];
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
// System.out.println("pos in id="+position);
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
Bitmap bitmap = DownloadImage(
kickerimage[position] );
// View listView = convertView;
if (convertView == null)
{
//this should only ever run if you do not get a view back
LayoutInflater inflater = (LayoutInflater) contxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.homelistrow, null);
}
// else
// {
// holder.removeAllViews();
// }
// View listView;
// if (convertView == null)
// {
// listView = new View(contxt);
// LinearLayout holder = (LinearLayout)convertView.findViewById(android.R.id);
//// holder = inflater.inflate(R.layout.homelistrow, null);
// System.out.println("pos="+position);
// System.out.println("item="+getItem(position));
// else
// {
TextView textView = (TextView) convertView
.findViewById(R.id.name_label);
textView.setText(itemsarray[position]);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.icon);
imageView.setImageBitmap(bitmap);
// }
// else
// {
// listView = (View) convertView;
// }
// }
return convertView ;
}
private Bitmap DownloadImage(String URL)
{
// System.out.println("image inside="+URL);
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("image last");
return bitmap;
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
Where i am going wrong??Please help me thanks in advance..
I solved it ..the problem lies in the line
Thread thread = new Thread();
Instead of this i done:
Thread thread = new Thread(Myactivity.this);
Now the Indicator is disappearing after loading.Thanks to all..

Using a HTTP Connection within an Android View Pager

I have 7 panels within my ViewPager. Each one has different functionality within it. For my news panel, I want to have functionality within the view. Here is the ViewPager class I am currently using:
class MyPageAdapter extends PagerAdapter {
public int getCount() {
//Return 7 as there will be 7 panes in the dashboard
return 7;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = null;
switch (position) {
case 0:
v = inflater.inflate(R.layout.dashboard_social, null);
break;
case 1:
v = inflater.inflate(R.layout.dashboard_unilife, null);
break;
case 2:
v = inflater.inflate(R.layout.dashboard_allcourses, null);
break;
case 3:
v = inflater.inflate(R.layout.dashboard_news, null);
//USE HTTP HERE FOR TWITTER FEED
break;
case 4:
v = inflater.inflate(R.layout.dashboard_mycourse, null);
break;
case 5:
v = inflater.inflate(R.layout.dashboard_media, null);
break;
case 6:
v = inflater.inflate(R.layout.dashboard_extras, null);
break;
}
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
I know that for a simple function such as using a button, you would have something like this:
case 3:
v = inflater.inflate(R.layout.dashboard_news, null);
//Functionality
Button btn = (Button) v.findViewById(R.id.bTutorialComplete);
final Context context = collection.getContext();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context,
DashboardContainerActivity.class));
}
});
My problem is that I have a separate Activity that retrieves the latest tweet from Twitter and displays it. Here is the code for displaying the latest tweet:
public class DashboardNews extends Activity{
TextView tvFeed;
HttpClient client;
//Incomplete URL of Twitter timeline
final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
//Used in AsyncTask to carry out lastTweet method
JSONObject json;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.twitter_feed);
tvFeed = (TextView) findViewById(R.id.tvTwitterFeedText);
new Read().execute("text");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException, JSONException{
//Used to create a string that can be appended
StringBuilder url = new StringBuilder(URL);
//append the username to the url
url.append(username);
//new HttpGet
HttpGet get = new HttpGet(url.toString());
//new response
HttpResponse r = client.execute(get);
//get status code
int status = r.getStatusLine().getStatusCode();
//check if status code is success (200)
if(status == 200){
//Get the entity from response
HttpEntity e = r.getEntity();
//Convert entity data to string
String data = EntityUtils.toString(e);
//Get JSON formatted sequence of values
JSONArray timeline = new JSONArray(data);
//Place the sequence in a JSONObject
JSONObject lasttweet = timeline.getJSONObject(0);
//return the last tweet
return lasttweet;
} else {
//Display a Toast that there was an error
Toast.makeText(getBaseContext(), "Error connecting to Twitter.", Toast.LENGTH_SHORT).show();
//Return null
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
//Call lastTweet method and username
json = lastTweet("kibria3");
//return the last tweet
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Set the text of view to the result
tvFeed.setText(result);
}
}
}
My question is how do I get this Activity working within case 3 of my switch statement for the View Pager? (replacing the button functionality with the HTTP Connection)

Http image parsing problem

I'm trying to set different images by parsing, but I can set only last image. I don't know where the problem is in this code:
public class GridActivity extends Activity{
private EfficientAdapter adap;
String strUrl;
AddAlbumDetailBean aBean;
XmlParser parser;
ArrayList<Object> result;
ArrayList<Object> data;
ImageButton btnAdd;
private Context context;
static Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.photos_activity);
GridView gView = (GridView)findViewById(R.id.gridview);
adap = new EfficientAdapter(this);
gView.setAdapter(adap);
/*btnAdd = (ImageButton)findViewById(R.id.btnAddPhotos);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(GridActivity.this,AddAlbum.class));
}
});
*/
}
public static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
String strUrl;
AddAlbumDetailBean aBean;
XmlParser parser;
ArrayList<Object> result;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
String userId = ConstantData.user_id;
String albumId = ConstantData.album_id;
int pageNo = 1;
int limit = 20;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=photo_paging&userid="+ ConstantData.user_id +"&sessionid="+ ConstantData.session_id +"&tmpl=component&albumid="+ ConstantData.album_id +"&pageno=1&limit=20");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><pageno>" + pageNo +"</pageno><limit>"+ limit +"</limit></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);
HttpResponse response = client.execute(post);
InputStream in = response.getEntity().getContent();
String strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "data");
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startT = strResponse.indexOf(startThumb);
int endT = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startT);
Log.i("endThumb", ""+endT);
String OldThumb = strResponse.substring(startT, endT);
int startUrlindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startUrlindex + 1).trim();// getting Url from webservice
Log.i("Thu0mb", ""+thumb);
URL newurl = new URL(thumb);
bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());// converting Url into Bitmap but dont know how to use bitmap array here
Log.d("Bitmap in ConstantData", ""+bitmap);
}
if (startUrl.equalsIgnoreCase("<url>") && endUrl.equalsIgnoreCase("</url>"))
{
int startL = strResponse.indexOf(startUrl);
int endL = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startL);
Log.i("endUrl", ""+endL);
String OldUrl = strResponse.substring(startL, endL);
int startUrlindex = OldUrl.indexOf(">");
String url = OldUrl.substring(startUrlindex + 1).trim();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.icon, null);
holder = new ViewHolder();
holder.iconImage = (ImageView) convertView.findViewById(R.id.icon_image);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context, "Click-" + String.valueOf(pos), Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context,GridActivity.class));
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("Bitmap in ConstantData", ""+bitmap);
holder.iconImage.setImageBitmap(bitmap);
return convertView;
}
static class ViewHolder {
ImageView iconImage;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5; // if i m trying to return result.size(); getting error and returning 5 i can only get 5 images
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
public static String convertStreamToString(InputStream in)
throws IOException {
if (in != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}
Through this code i am trying to set image into the dynamic gridview using adapter....
but i can set only last image into the gridview so i dont know how to use bitmap array
There are a lot of problems on your code:
your bitmap is static, so you overriding it...
you have no loop, so you have only the same bitmap "parsed"
(after that I stopped looking)
Try to clean up your code and try to debug step by step so that you understand what your code does...
update:
some tips:
use AsyncTask to request the XML and parse it there
when finished fill the adapter with the parsed image urls

Categories

Resources