What is wrong with this code? - java

Sorry that I'm asking such a question, but I'm tryin to make this one run for hours, and I'm not finding the mistake...
public class Main extends ListActivity {
/** Called when the activity is first created. */
ProgressDialog dialog;
#Override
public synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new WebLoader().doInBackground("http://sample.sample.com/sample.xml");
}
public class WebLoader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try{
URL url = new URL(params[0]);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(2048);
int current = 0;
while((current = bis.read()) != -1)
{
baf.append((byte)current);
}
result = new String(baf.toByteArray());
}
catch(Exception e)
{
Log.e("gullinews", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getApplicationContext(), "",
"Loading. Please wait...", true);
}
}
}
Running with a debugger shows, that the xml data is downloaded, but there's just black screen. When I tried "setContenView(R.layout.main);" with main.xml:
<?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"
>
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#android:id/list" />
</LinearLayout>
//Edit:
okay, I solved one error, didn't solve the rest. Source updated.
My Main problem now is, that I ain't got an Idea why the ProgressDialog doesnt show up. rest should be black, that's right.

new WebLoader().doInBackground("http://sample.sample.com/sample.xml");
That's not how you use an asynctask. Did you read any documentaton at all?

Related

Async Task Attemp to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Im Getting invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at app.VOTD_Data.onPostExecute.
Async Task
public class VOTD_Data extends AsyncTask<Void, Void, Void> {
private String verseData = "";
private String dailyverse = "";
private String verseauthor = "";
private String dailVersePref = "";
private String verseAuthorPref = "";
private SharedPreferences sharedPreferences;
private Context context;
public VOTD_Data(Context context){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
dailVersePref = sharedPreferences.getString("dailyverse", "");
verseAuthorPref = sharedPreferences.getString("verseauthor", "");
}
public VOTD_Data() {
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://beta.ourmanna.com/api/v1/get/?format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
verseData = verseData + line;
}
JSONObject mainObject = new JSONObject(verseData).getJSONObject("verse");
JSONObject verseObject = mainObject.getJSONObject("details");
dailyverse = verseObject.getString("text");
verseauthor = verseObject.getString("reference");
sharedPreferences
.edit()
.putString("dailyverse", dailyverse)
.putString("verseauthor", verseauthor)
.apply();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Daily Verse Activity
DailyVerse_Activity.data.setText(dailyverse.toString());
}
}
Main Activity
public class DailyVerse_Activity extends AppCompatActivity {
public static TextView data;
private ImageView banner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_verse);
data = (TextView) findViewById(R.id.dataText);
VOTD_Data process = new VOTD_Data(DailyVerse_Activity.this);
process.execute();
}
//On Back Pressed
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
finish();
return true;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".DailyVerse_Activity">
<TextView
android:id="#+id/dataText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:gravity="center"
android:hint="Verse Data"
/>
</RelativeLayout>
Im Getting invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at app.VOTD_Data.onPostExecute.app.VOTD_Data.onPostExecute(VOTD_Data.java:88)
at app.VOTD_Data.onPostExecute(VOTD_Data.java:18)
Pass your rootView to AsyncTask and get it's reference from there. Add one more parameter in your VOTD_Data class like this.
public VOTD_Data(Context context, TextView textView)
In postExecute just do:
textView.setText(dailyverse.toString());
And in your Activity class while calling the AsyncTask pass the textView to VOTD_Data class constructor like this:
VOTD_Data process = new VOTD_Data(DailyVerse_Activity.this, data);
process.execute();

How to go from one fragment to another, from an other java class?

I have a login page on fragment connected to BackgroundWorker class which has database connectivity.
my login page sends texts from EditTexts to BackgroundWorker Class, then all the database queries(by accessing PHP files from WAMP) are done in the BackgroundWorker class.
When i click the login button on my fragment it opens the dialog box which tells me if login was successful or not. (the code of dialog box exists in BackgroundWorker class (Please refer the code if i am not being clear) )
but the thing is, i don't want dialog box, i want to go from one fragment to another from that BackgroundWorker.java file.
i have the code of how can i go from one activity to another, but not of fragment
fragment 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.admin.blingiton.Client_login">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:id="#+id/ClientLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="600dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:scaleType="fitXY"
app:srcCompat="#drawable/back" />
<ImageView
android:id="#+id/mirae"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="12dp"
android:layout_marginStart="32dp"
android:scaleType="centerInside"
app:srcCompat="#drawable/mirae" />
<ImageView
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="600dp"
android:layout_alignBottom="#+id/mirae"
android:layout_alignParentStart="true"
android:layout_marginBottom="20dp"
android:scaleType="fitStart"
app:srcCompat="#drawable/header" />
<EditText
android:id="#+id/cusername"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_alignTop="#+id/mirae"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:background="#drawable/username"
android:ems="10"
android:hint="username"
android:inputType="textPersonName"
android:textAlignment="center" />
<EditText
android:id="#+id/cpassword"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_alignStart="#+id/cusername"
android:layout_below="#+id/cusername"
android:layout_marginTop="18dp"
android:background="#drawable/password"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
android:textAlignment="center" />
<Button
android:id="#+id/clogin"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_above="#+id/signupbtn"
android:layout_alignStart="#+id/cpassword"
android:layout_marginBottom="11dp"
android:background="#drawable/login" />
<Button
android:id="#+id/signupbtn"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_alignBottom="#+id/mirae"
android:layout_alignStart="#+id/clogin"
android:background="#drawable/signup"
/>
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/log" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/afterlogin"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</RelativeLayout>
Fragment.java file
EditText UsernameEt, PasswordEt;
Button login;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_clientlogin, container, false);
UsernameEt = (EditText) v.findViewById(R.id.cusername);
PasswordEt = (EditText) v.findViewById(R.id.cpassword);
login = (Button) v.findViewById(R.id.clogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new
BackgroundWorker(getActivity());
backgroundWorker.execute(type, username, password);
}
});
return v;
}
BackgroundWorker.java < /b>
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String...params) {
String type = params[0];
String login_url = "http://192.168.10.2/login.php";
if (type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-
8 ")+" = "+URLEncoder.encode(user_name,"
UTF - 8 ")+" & " +
URLEncoder.encode("password", "UTF-
8 ")+" = "+URLEncoder.encode(password,"
UTF - 8 ");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream, "iso-8859-1"));
String result = ""; String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
Client_login cl = new Client_login();
alertDialog.setMessage(result);
//alertDialog.show();
if (result.contentEquals("login success !!!!! Welcome user")) {
//Code Here.
} else {
Toast toast = Toast.makeText(context, "Email or password is wrong",
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onProgressUpdate(Void...values) {
super.onProgressUpdate(values);
}
try to use this if you find any error please let me know.
First create a interface
interface ChangeFragment
{
public void chfragment();
}
Then your second fragment
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// this is your success login fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}
}
After that your activity where you place the login fragment
public class Successfull extends Activity implements ChangeFragment
{
protected void onCreate(android.os.Bundle savedInstanceState) {
//your code
}
}
#Override
public void chfragment()
{
SecondFragment yoursecondfragment=new SecondFragment();
FragmentManager manager=getSupportedFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.layout.framelayout,yoursecondfragment);
transaction.commit();
}
}
then your backgroundworker thread
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.10.2/login.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection =
(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-
8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-
8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
Client_login cl = new Client_login();
alertDialog.setMessage(result);
//alertDialog.show();
if(result.contentEquals("login success !!!!! Welcome user")) {
//Code Here.
ChangeFragment frag=new Successfull();
frag.chfragment();
}else
{
Toast toast= Toast.makeText(context, "Email or password is wrong",
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
I think this code will help you.

Image URL entered In editText on a imageView

When the user clicks this button the app should retrieve the image from the web. It should do this in a separate thread and When the image is downloaded it should be displayed on the same Screen using ImageView.I can't seem to get it to work but I feel like I'm really close can anyone help me out please? Thanks!
My Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stephen.asyncdownloadimageurl">
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My XML FIle
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#android:drawable/alert_light_frame"
android:layout_marginBottom="146dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="91dp" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp"
android:ems="10" />
My Jave File
public class MainActivity extends AppCompatActivity {
Button btn;
EditText et;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
et = (EditText) findViewById(R.id.editText);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
URL url = new URL(et.getText().toString());
new MyDownloadTask().execute(url);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(URL... params) {
URL url = params[0];
Bitmap bitmap = null;
try {
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
}
}
}
}
Use special android libraries like Glide or Picasso to load images. It's really easy to use it, they have disk/memory cache, you can load image in separate thread without using complex solutions.
As you mentionned in a comment, your image is at this url
http://tny.im/ayy
This url does not point to an image. It points to a redirects, (http status 301).
It is possible that your connection is not following redirects.
You can instruct the connection to follow the redirection by:
((HttpURLConnection) connection).setInstanceFollowRedirects(true);
Ok so here is my thoughts after talking in the comments
1) I copied your code and xml EXACTLY as you posted and it WORKS fine for me, with that said I want to add a few things
EDIT: not sure if this matters but these were my imports
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
I think it could be a combination of these possibilities
2) make sure your url is ok, make sure you add the http or https part. make sure your auto correct does not add anything (mine added a period at the end). since this is the only part I can't test, I feel like this could be it
3) Log everything, log the url right before its passed into your URL object just to be sure it is correct, look for ANY exceptions
4) the toast will not show up if url is wrong, if url can't parse a valid URL ( like mentioned earlier), it will be caught in the try catch surrounding the URL object being created and will not call the async task (happen to me when I put fake url in and I got exception, so try keep an eye out)
EDIT: for number 4, i got exception for incorrect protocol (left out the http) but if link was wrong then yes, toast showed up
5) try another image, you never know :D
EDIT: try this with Glide,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
et = (EditText) findViewById(R.id.editText);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Glide.with(MainActivity.this)
.load(et.getText().toString())
.into((ImageView) findViewById(R.id.imageView));
} catch (Exception e) {
e.printStackTrace();
}
}
no need for async
and one more solution without Glide
#Override
protected Bitmap doInBackground(URL... params) {
URL url = params[0];
HttpURLConnection connection = null;
Bitmap bitmap = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
// Add following dependecny for glide
compile 'com.github.bumptech.glide:glide:3.7.0'
new LoadImageFromUrlTask().execute(imageURL);
public class LoadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
String downloadPath = "";
String sdCardBasePath = Environment.getExternalStorageDirectory().toString();
#Override
protected Bitmap doInBackground(String... args) {
try {
downloadPath = args[0];
return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
String saveImagePath = "";
int dotposition = photoFileName.lastIndexOf(".");
String filename_Without_Ext = photoFileName.substring(0, dotposition);
String Ext = photoFileName.substring(dotposition + 1, photoFileName.length());
String newFileName = filename_Without_Ext + "." + Ext;
saveImagePath = sdCardBasePath + "/" + newFileName;
saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
saveBitmapToFile(MainActivity.this, myImageViewImage, saveImagePath);
} else {
myImageViewImage.setImageResource(R.drawable.default_photo);
}
}
}
public Boolean saveBitmapToFile(Context ctx, Bitmap tempBitmap, File targetFile, int i) {
Boolean result = true;
if (tempBitmap != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(targetFile);
tempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out);
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
result = false;
}
return result;
}
public void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
Glide.with(theCtx)
.load(theUrl)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(theImageView);
}
I couldn't get the code I originally posted to work even with all of you's guys help. Big thanks to anybody that posted with suggestions!!. Anyway I went back to scratch and finally got it to work with even less code!
Here's my working code
public class MainActivity extends AppCompatActivity {
EditText editText;
Bitmap bitmap;
ImageView view;
Button btn;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.inputFileUrl);
view = (ImageView) findViewById(R.id.imageView);
btn = (Button) findViewById(R.id.retrieveFileUrl);
}
public void buttonClicked(View view) {
String stringUrl = editText.getText().toString();
new DownloadTask().execute(stringUrl);
}
// Uses AsyncTask to create a task away from the main UI thread. This task takes
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
public class DownloadTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
//Create PD, SET Properties
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Image Downloader");
pd.setMessage("Downloading....");
pd.setIndeterminate(false);
pd.show();
}
#Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
try {
bitmap = BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(Bitmap url) {
if (bitmap != null) {
super.onPostExecute(url);
view.setImageBitmap(url);
//Dismiss
pd.dismiss();
} else {
Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
//Dismiss
pd.dismiss();
}
}
}
}
Use library like Glide. You can simply add Glide dependency in Gradle:
compile 'com.github.bumptech.glide:glide:3.7.0'
and you can load image simply by writing:
Glide.with(context).load("image_url").into(imagevie_name);

Android Calling API and parsing JSON

Trying to make an API call to the url below and parse the returning JSON, when the "refresh" button is called.
I can link to a button and get text (Hello world) to the screen, but can't seem to link the button click to the API request. Error message says I cannot reference non-static method "execute" from a static context
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void retrieveInformation(View view){
RetrieveFeedTask.execute();
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
String jsonString = "";
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL("www.liftin.co.uk/api/v1/journeys");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
jsonString = response;
try {
getInformationFromJson(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getInformationFromJson(String jsonString)
throws JSONException {
final String DRIVER = "driver";
final String START = "start";
final String DESTINATION = "destination";
final String TIME = "pick_up_time";
final String PASSENGERS = "passengers";
final String SEATS = "seats_available";
JSONObject journeyJson = new JSONObject(jsonString);
String time = journeyJson.getString(TIME);
String seats = journeyJson.getString(SEATS);
String results = seats + "-----" + time;
return results;
}
}
}
Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.liftin.MainActivity">
<Button
android:id="#+id/queryButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Refresh"
android:onClick="retrieveInformation"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/responseView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
</LinearLayout>
You should create asynchronous call for your AsyncTask like this :
public void retrieveInformation(View view){
new RetrieveFeedTask().execute(); //asynchronous call
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
UPDATE
If you want to set data to textview after parsing data. You have to make little bit changes in your activity as follows.
You should initialize your textview in onCreate() and make it global variable for your activity, so that you can access it in full activity.
then in your onPostExecute() do this :
textview.setText(getInformationFromJson(response));
Hope it will Help :)
You must create a object of AsyncTask (RetrieveFeedTask) before calling it. For example
public void retrieveInformation(View view){
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
new RetrieveFeedTask().execute();
}
You still need to pass something for Void.
public void retrieveInformation(View view){
new RetrieveFeedTask().execute(null);
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}

Displaying picture, name and description in a listView android

Im trying to display some information from my Items[] in a listview, the information is retrived from database. what I want to display is a picture, name and description. note that the picture is retrived in base64 string so I have to convert it before sending data.
I tried this:
for(int x=0;x<items.length;x++) {
byte[] decodedString = Base64.decode(items[x].Picture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
ListAdapter adapter = new SimpleAdapter(Itemlist.this, (List<? extends Map<String, ?>>) listView, R.layout.layout, new String[]{items[x].Name, items[x].Description}, new int[]{R.id.move_title, R.id.move_rating});
setListAdapter(adapter);
}
but I got this error:
java.lang.ClassCastException: android.widget.ListView cannot be cast to java.util.List
this is the activity layout:
<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" tools:context=".MainActivity"
android:background="#ffffff"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
and the list layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#ffffff"
>
<ImageView
android:id="#+id/move_poster"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#FFFFFF"
android:layout_alignRight="#+id/move_poster"
android:layout_alignEnd="#+id/move_poster"
android:layout_below="#+id/move_poster">
</View>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/move_title"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/move_poster"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/move_rating"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/move_title"
android:layout_toRightOf="#+id/move_poster"
android:layout_toEndOf="#+id/move_poster"
android:layout_alignBottom="#+id/move_poster" />
</RelativeLayout>
and this is the whole activity class:
public class Itemlist extends ListActivity {
private Handler mHandler= new Handler();
Item[] items;
ListView listView;
MoveAdapter adapter;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_itemlist);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView=getListView();
tv=(TextView)findViewById(R.id.textView);
String[] params= new String[]{"192.168.1.11:90"};
new MyAsyncTask().execute(params);
}
class MyAsyncTask extends AsyncTask<String, Void, String>
{
public String SOAP_ACTION="http://tempuri.org/GetAllItems";
public String OPERATION_NAME ="GetAllItems";
public String WSDL_TARGET_NAMESPACE ="http://tempuri.org/";
public String SOAP_ADDRESS;
private SoapObject request;
private HttpTransportSE httpTransport;
private SoapSerializationEnvelope envelop;
Object response= null;
#Override
protected String doInBackground(String... params) {
SOAP_ADDRESS = "http://" + params[0] + "/myWebService2.asmx";
request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelop.dotNet = true;
envelop.setOutputSoapObject(request);
httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelop);
SoapObject response = (SoapObject) envelop.getResponse();
items = new Item[response.getPropertyCount()];
for (int i = 0; i < items.length; i++) {
SoapObject pii = (SoapObject) response.getProperty(i);
Item item = new Item();
item.Name = pii.getProperty(0).toString();
item.Description = pii.getProperty(1).toString();
item.Picture = pii.getProperty(2).toString();
item.ID = Integer.parseInt(pii.getProperty(3).toString());
items[i] = item;
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Done"; }
#Override
protected void onPostExecute(final String result){
super.onPostExecute(result);
mHandler.post(new Runnable() {
#Override
public void run() {
tv.setText(result);
for(int x=0;x<items.length;x++) {
byte[] decodedString = Base64.decode(items[x].Picture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
ListAdapter adapter = new SimpleAdapter(Itemlist.this, (List<? extends Map<String, ?>>) listView, R.layout.layout, new String[]{items[x].Name, items[x].Description}, new int[]{R.id.move_title, R.id.move_rating});
setListAdapter(adapter);
}
}
});
}
}
}
also I don't know how to send the bitmap format of the picture to the adapter, because it only takes Strings.
can someone please help me displaying the listview of images, name and description?
Actually i think i have some time to do it now,
here we go.
but first you need to read and learn Custom adapter for listView
you can google it and understand how it works,
then come back to this answer.
here you can findsome good sample for a custom adapter
you really need to read and understand it.
now, some code changes for your's
1- modify your Item class to have a Bitmap Member
public Bitmap bitmap;
adding setter and getter is better. but you can make it public and access it directly
2- [Optional] in Itemlist activity, declare Arraylist instead of array
you will learn more about this when you search for custom adapter, as you can pass data as Array or as List
private ArrayList<Item> items = new ArrayList();
3- modify the for loop as following: (assuming you did not changed to arrayList and still use array[])
for(int x=0;x<items.length;x++) {
byte[] decodedString = Base64.decode(items[x].Picture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
items[x].bitmap = decodedByte;
}//for loop end
4- declare adapter (instance of your Custom Adapter), and assign it to the listView
MyCustomAdapter adapter = new MyCustomAdapter(ItemsList.this, R.layout.list_row, items);
setListAdapter(adapter);
now in your adapter's getView() method, you can use the memebrs (name, desc, bitmap) to populate the custom layout of each row
that's it.
P.S: this code is not all compiled, and may contain some typos,
it's just to guide you through the process.

Categories