I was building a app involving a video player, i have a list view which displays a list of videos and clicking on any of those should play that video. The links i use are rstp youtube links & the video plays fine but when i click back button after the video is played & come to the list again i get Sorry video cant be played error.
Here is my video player class & the list Class:
Video Player class:
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single);
vid=(VideoView) findViewById(R.id.svid);
iv=(ImageView) findViewById(R.id.simg);
ip=(ImageView) findViewById(R.id.playimg);
t=(TextView) findViewById(R.id.textView1);
final ProgressDialog pd=new ProgressDialog(SingleItem.this);
Intent g=getIntent();
thumb=g.getStringExtra("thumb");
link=g.getStringExtra("link");
msg=g.getStringExtra("msg");
//link="rtsp://v7.cache5.c.youtube.com/CjYLENy73wIaLQmgwjdV-8ZI5BMYJCAkFEIJbXYtZ29vZ2xlSARSBWluZGV4YKSf0bH1u4jEUAw=/0/0/0/video.3gp";
String path1=link;
MediaController mc = new MediaController(this);
mc.setAnchorView(vid);
mc.setMediaPlayer(vid);
uri=Uri.parse(path1);
vid.setMediaController(mc);
vid.setVideoURI(uri);
// vid.requestFocus();
//iv.setClickable(true);
loadImage(thumb);
t.setText(msg);
ip.setClickable(true);
ip.setImageResource(R.drawable.play);
// ip.setVisibility(ImageView.INVISIBLE);
vid.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
//ip.setVisibility(ImageView.VISIBLE);
pd.dismiss();
}
});
ip.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vid.start();
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Loading Video...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
if(vid.isPlaying()){
iv.setVisibility(ImageView.INVISIBLE);
ip.setVisibility(ImageView.INVISIBLE);
}else{
iv.setVisibility(ImageView.VISIBLE);
ip.setVisibility(ImageView.VISIBLE);
vid.stopPlayback();
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
vid.stopPlayback();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
vid.stopPlayback();
}
void loadImage(String image_location){
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
iv.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My List class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf=new PrefMethods(this);
e=(EditText) findViewById(R.id.editText1);
go=(Button) findViewById(R.id.bGo);
e.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#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
if(e.getText().length()==0){
adapter=new LazyAdapter(VideoList.this, myList);
//Toast.makeText(getApplicationContext(), "Here finally", 500).show();
list.setAdapter(adapter);
}
}
});
ArrayList<String> items = new ArrayList<String>();
myList = new ArrayList<HashMap<String, String>>();
arr_link = new ArrayList<String>();
arr_thumb = new ArrayList<String>();
arr_msg = new ArrayList<String>();
allItems=new ArrayList<HashMap<String, String>>();
try {
URL urlnew= new URL("link");
HttpURLConnection urlConnection =
(HttpURLConnection) urlnew.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// gets the server json data
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String next;
while ((next = bufferedReader.readLine()) != null){
JSONArray ja = new JSONArray(next);
int k=ja.length();
vid_id=pf.loadprefs();
//Toast.makeText(getApplicationContext(), "Here", 500).show();
for (int i = 0; i < ja.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jo = (JSONObject) ja.get(i);
WaveData waveData = new WaveData(jo.getString("VUpload"), jo.getInt("recid"),jo.getString("VYoutube"),jo.getString("VMessage"),jo.getString("VThumb"));
if(jo.getInt("recid")>vid_id){
if(i==k-1){
pf.saveprefs(jo.getInt("recid"));
//vid_id=2;
vid_id=jo.getInt("recid");
//Toast.makeText(getApplicationContext(), ""+vid_id, 500).show();
}else{}
}else{}
if(jo.has("VUpload")){
map.put("msg", jo.getString("VMessage"));
map.put("youtube", jo.getString("VYoutube"));
map.put("thumb", jo.getString("VThumb"));
// Toast.makeText(getApplicationContext(), "Here too", 500).show();
myList.add(map);
//Toast.makeText(getApplicationContext(), jo.getString("VMessage"), 500).show();
items.add(jo.getString("VMessage"));
arr_msg.add(jo.getString("VMessage"));
arr_link.add(jo.getString("VYoutube"));
arr_thumb.add(jo.getString("VThumb"));
}
}
}
} catch (MalformedURLException 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();
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, myList);
//Toast.makeText(getApplicationContext(), "Here finally", 500).show();
list.setAdapter(adapter);
//Toast.makeText(getApplicationContext(), "Set List ", 500).show();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String l=list.getAdapter().getItem(arg2).toString();
Toast.makeText(getApplicationContext(), l, 500).show();
String sthumb=arr_thumb.get(arg2);
String slink=arr_link.get(arg2);
String smsg=arr_msg.get(arg2);
Intent vid=new Intent(getApplicationContext(), SingleItem.class);
vid.putExtra("link", slink);
vid.putExtra("msg", smsg);
vid.putExtra("thumb", sthumb);
startActivity(vid);
}
});
go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
allItems.clear();
String l= e.getText().toString();
for(int g=0;g<vid_id;g++){
if(myList.get(g).containsValue(l)){
allItems.add(myList.get(g));
}
}
adapter=new LazyAdapter(VideoList.this, allItems);
// Toast.makeText(getApplicationContext(), "Here finally", 500).show();
list.setAdapter(adapter);
}
});
}
}
The video list gets loaded no issues & even the video plays but when i click the back button it comes back to list & says Sorry,this video cant be played !
Any ideas why the error?
Thanks in advance guys !
Fixed this issue, all i did was made the video stop playing in the onPause & onDestroy method.
Now it works fine without any error
Related
In my application I have a fragment which loads image from remote server to set background of FrameLayout using AsynTask and in onPostExeccute() method I am trying to render Bitmap images using Picasso. But as my Fragment starts first time no image is loaded in the background of FrameLayout but as I refresh the particular fragment then I can see the Image as background.
Updated Code segment inside AsyncTask
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String responseBody = "";
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(ctx, "Server connection failed", Toast.LENGTH_LONG).show();
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == -1){
Toast.makeText(ctx, "Sorry No Places Found", Toast.LENGTH_LONG).show();
}
if(jsonResult == 1){
//Toast.makeText(ctx, "", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObj = new JSONObject(result);
// Getting JSON Array node
places = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < places.length(); i++) {
JSONObject place = places.getJSONObject(i);
// String slot = c.getString(TAG_SLOT);
// serverReturn.add(slot);
UserPlaces placeFroServer = new UserPlaces();
placeFroServer.setId(place.getString(TAG_PID));
placeFroServer.setName(place.getString(TAG_PNAME));
placeFroServer.setDescription(place.getString(TAG_DESC));
placeFroServer.setImg(place.getString(TAG_IMG));
placeFroServer.setLat(place.getString(TAG_LAT));
placeFroServer.setLng(place.getString(TAG_LNG));
placesList.add(placeFroServer);
}
UserPlaces myPlace = placesList.get(counter);
pid=myPlace.getId();
lat = myPlace.getLat();
lng = myPlace.getLng();
Picasso.with(ctx).load(myPlace.getImg()).into(new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
// TODO Auto-generated method stub
Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
pImg.invalidate();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
}
});
pname.setText(myPlace.getName());
pdes.setText(myPlace.getDescription());
rl.setVisibility(View.VISIBLE);
counter++;
} catch (JSONException e) {
String ex = e.getMessage();
e.printStackTrace();
}
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
For particular problem of week reference try creating a global Target object. As demonstrated in the code below.
Code Sample:
Target target;
target = new Target(){
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
//Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
pImg.invalidate();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
}
};
Picasso.with(ctx).load(myPlace.getImg()).into(target);
You should call invalidate() on pImg after setting the background.
You can use the alternative of it Univerasal Image Loader
This question already has an answer here:
What is the simplest way in Android to keep an objects value after every app run?
(1 answer)
Closed 7 years ago.
I have an android chat application that sends messages from client to server but I am looking for a way to store the send messages in some way, other than being displayed in the list.
Here is part of my application;
public class AndroidChatApplicationActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
// msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
Button twitterButton = (Button) findViewById(R.id.website_Button);
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendToWebsite();
}
});
}
protected void sendToWebsite() {
String url = "https://www.ljmu.ac.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
// receiveMsg();
// ----------------------------
// server msg receieve
// -----------------------
// End Receive msg from server//
public void sendMessageToServer(String str) {
final String str1 = str;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// String host = "opuntia.cs.utep.edu";
String host = "10.0.2.2";
String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
// out.println("hello");
out.println(str1);
Log.d("", "test");
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test3");
}
}
}).start();
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// final String host="opuntia.cs.utep.edu";
final String host = "10.0.2.2";
// final String host="localhost";
Socket socket = null;
BufferedReader in = null;
try {
socket = new Socket(host, 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
Log.d("", "MSGGG: " + msg);
// msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("", "Hi Test");
}
});
}
}
Could anyone suggest a method of storing the messages other than displaying them in a list?
You can try storing them in SharedPreferences. By what I gather, you want store the input so that you can later look at then in a different activity. Have a look at SharedPreferences here http://developer.android.com/reference/android/content/SharedPreferences.html
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.....
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.
below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.