I am making an app which will display the images of celebrities and 4 names out of which one is correct.
I have added a button "change" to change the celebrity in the image, but on pressing that button my app is crashing showing null java.lang.null pointer exception.
I have the the code for loading the image and four names in the oncreate method which loads the image and four names when the app is first started, but on pressing the button when the function is invoked , error is generated although i have that same code in it.
public class MainActivity extends AppCompatActivity {
//declaring all the widgets to be used
Bitmap celebimg;
Random rand;
ImageView img;
Button btn0, btn1, btn2, btn3;
int optionnum, imgnum;
ArrayList<String> celebnames = new ArrayList<String>();
ArrayList<String> celebimages = new ArrayList<String>();
ArrayList<String> buttonoptions = new ArrayList<String>();
//Invoked when one out of the four options is clicked
public void row(View view) {
if (view.getTag().toString().equals(Integer.toString(optionnum))){
Toast.makeText(this, "correct Answer", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "wrong Answer, It was" +
celebnames.get(imgnum), Toast.LENGTH_SHORT).show();
}
}
//Class for downloading of image
public class Imagedownload extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myimage = BitmapFactory.decodeStream(in);
return myimage;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/**
* Class for downloading the website html code
*/
public class Download extends AsyncTask<String, Void, String > {
#Override
protected String doInBackground(String... strings) {
String result = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL(strings[0]);
connection = (HttpURLConnection)url.openConnection();
InputStream input = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int data = reader.read();
while(data != -1) {
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Code to execute when the change button is clicked
public void change(View view) {
rand = new Random();
imgnum = rand.nextInt(celebimages.size());
Imagedownload image = new Imagedownload();
try {
celebimg = image.execute(celebimages.get(imgnum)).get();
if (celebimg == null)
Log.i("its", "null douchebag");
img.setImageBitmap(celebimg);
} catch (InterruptedException e) {
if (celebimg == null)
Log.i("its", "null douchebag");
e.printStackTrace();
} catch (ExecutionException e) {
if (celebimg == null)
Log.i("its", "null douchebag");
e.printStackTrace();
}
optionnum = rand.nextInt(4);
for(int i = 0;i < 4;i++){
if(i == optionnum)
buttonoptions.add(celebnames.get(imgnum));
else {
int random = rand.nextInt(celebnames.size());
while (celebnames.get(imgnum) == celebnames.get(random)){
random = rand.nextInt(celebnames.size());
}
buttonoptions.add(celebnames.get(random));
}
}
btn0.setText(buttonoptions.get(0));
btn1.setText(buttonoptions.get(1));
btn2.setText(buttonoptions.get(2));
btn3.setText(buttonoptions.get(3));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.celeb);
btn0 = (Button)findViewById(R.id.btn0);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
String data = "";
Download load = new Download();
try {
data = load.execute("http://www.posh24.se/kandisar").get();
String[] splitdata = data.split("<div class=\"title\">Lista:</div>");
// seperating out the required img src from the html code
Pattern p = Pattern.compile("src=\"(.*?)\"");
Matcher M = p.matcher(splitdata[1]);
while (M.find()){
//adding all the img src values to celebimages arraylist
celebimages.add(M.group(1));
}
Pattern pi = Pattern.compile("alt=\"(.*?)\"");
Matcher Mi = pi.matcher(splitdata[1]);
while (Mi.find()) {
// adding all the alt values to celebnames arraylist
celebnames.add(Mi.group(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Random rand = new Random();
imgnum = rand.nextInt(celebimages.size());
Imagedownload image = new Imagedownload();
Bitmap celebimg;
try {
//downloading the image from stored img src values from celebimages
//arraylist
celebimg = image.execute(celebimages.get(imgnum)).get();
img.setImageBitmap(celebimg);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//Setting the correct value in one button and random values in other
//three
optionnum = rand.nextInt(4);
for(int i = 0;i < 4;i++){
if(i == optionnum)
buttonoptions.add(celebnames.get(imgnum));
else {
int random = rand.nextInt(85);
while (celebnames.get(imgnum) == celebnames.get(random)){
random = rand.nextInt(celebnames.size());
}
buttonoptions.add(celebnames.get(random));
}
}
btn0.setText(buttonoptions.get(0));
btn1.setText(buttonoptions.get(1));
btn2.setText(buttonoptions.get(2));
btn3.setText(buttonoptions.get(3));
}
Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
The problem is because you're creating another variable for the image instead reusing the previous variable:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.celeb);
...
}
it should be
img = (ImageView)findViewById(R.id.celeb);
The problem usually happens because not using a readable naming convention such as the following:
Bitmap celebimg;
Random rand;
ImageView img;
Button btn0, btn1, btn2, btn3;
Use something like this for class scope variables:
Bitmap mBmpCeleb;
Random mRndSomeId;
ImageView mImvCeleb;
Button mBtnImageOne, mBtnImageTwo, mBtnImageThree, mBtnImageThree;
where the m character is an abbreviation of member which is telling that the variable is member of the class.
Use something like the following for a method scope variable:
ImageView imvCeleb = (ImageView) findViewById(R.id.celeb);
Related
I'm new in Android and I'm trying to understand the right architecture to print files using android. I read about Print Manager, Print service, print job, etc..., but I didn't find a good and simple example from where to start. I did some proof, but I can't get a result.
My target is to print a label or just a string on a Zebra printer. I'm using ip address to connect my app andorid to printer. I found out two example.
The first example:
String ipAddress = "X.X.X.X";
int port = 9100;
PrintStream oStream;
try {
Socket client = new Socket(ipAddress, 9100);
oStream = new PrintStream(client.getOutputStream(), true, "UTF-8");
oStream.println("-------------------------------------------------\r\n");
oStream.println(" NAME : DEMO CLIENT\r\n");
oStream.println(" CODE : 00000234242\r\n");
oStream.println(" ADDRESS : Street 52\r\n");
oStream.println(" Phone : 2310-892345\r\n");
oStream.println("-------------------------------------------------\r\n");
oStream.flush();
oStream.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
And second example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_document_test);
FONT11 = 10;
FONT12 = 11;
FONT14 = 13;
FONT16 = 15;
btnCreate = (Button)findViewById(R.id.create);
editText =(EditText) findViewById(R.id.edittext);
btnPrint = findViewById(R.id.btnPrint);
typeface = Typeface.createFromAsset(getAssets(), "fonts/impact.ttf");
gwen = Typeface.createFromAsset(getAssets(), "fonts/Gwendolyn-Regular.ttf");
bmp = BitmapFactory.decodeResource(getResources(),R.drawable.orizzontale_nero);
scaleBitmap = Bitmap.createScaledBitmap(bmp,50,20,false);
// = Typeface.createFromAsset(getApplicationContext().getAssets(), "impact.ttf");
//carlitoBold = Typeface.createFromAsset(getApplicationContext().getAssets(), "Carlito-Bold.ttf");
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//new LongOperation().execute(" ");
new LabelBarcodePDFTask().execute();
}
});
btnPrint.setOnClickListener(v ->{
new PrintPDF().execute();
} );
}
private class PrintPDF extends AsyncTask<Void,Void,Integer> {
#Override
protected Integer doInBackground(Void... voids) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(PdfDocumentTestActivity.this.getFilesDir()+ File.separator + "/mypdf/test-ITEXTPDF.pdf");
InputStream is = fileInputStream;
clientSocket = new Socket(sIP, Integer.parseInt(sPort));
outToServer = new DataOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[3000];
while (is.read(buffer) != -1) {
outToServer.write(buffer);
}
outToServer.flush();
return 1;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
private class LabelBarcodePDFTask extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... voids) {
String directory_path = PdfDocumentTestActivity.this.getFilesDir()+File.separator + "/mypdf/";
String targetPdf = directory_path+"test-ITEXTPDF1.pdf";
//Create layout and set background & borders
Rectangle layout = new Rectangle(PageSize.ARCH_A);
//layout.setBackgroundColor(new BaseColor(100, 200, 180)); //Background color
layout.setBorderColor(BaseColor.DARK_GRAY); //Border color
layout.setBorderWidth(6); //Border width
layout.setBorder(Rectangle.BOX);
Document document = new Document(layout);
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(targetPdf));
document.open();
PdfContentByte cb = writer.getDirectContent();
//Get width and height of whole page
float pdfPageWidth = document.getPageSize().getWidth();
float pdfPageHeight = document.getPageSize().getHeight();
/*document.add(new Paragraph("pdfPageWidth = "+pdfPageWidth));
document.add(new Paragraph("pdfPageHeight = "+pdfPageHeight));*/
Barcode39 barcode39 = new Barcode39();
barcode39.setCode("123456789");
Image code39Image = barcode39.createImageWithBarcode(cb, null, null);
document.add(code39Image);
document.newPage();
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return targetPdf;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), "File saved in "+s, Toast.LENGTH_SHORT).show();
}
}
Both solution work fine on Brother printer and OKI printer, but when I run on Zebra printer nothing happen.
I ask you if you can provide an example structure to start from. Something simple. Also if there is a way to understand what happens after hitting the print document button
I am making this news application in which I m finding difficulties. here I am using list view.here I am performing background task also and even in this I am able to fetch all the news. The only thing which is not working is when I click on list item its respective image is not showing.
How can I take the image from url and when clicked on the item, the image of that respective list is opened?
public class MainActivity extends AppCompatActivity
{
ListView aboutNews;
Bitmap myImage;
ImageView newnewImage;
ArrayAdapter<String> myArrayAdapter;
ArrayList<String> newscontent , urlImageContent;
String finalUrl;
public void DisplayNews(String title, String urlToImage) {
myArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, newscontent); //i will not put this on oncreate because it will slow down my app.
aboutNews.setAdapter(myArrayAdapter);
newscontent.add(title);
urlImageContent.add(urlToImage);
}
public class downloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String news = jsonObject.getString("articles");
JSONArray arr = new JSONArray(news);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = jsonPart.getString("title");
String description = jsonPart.getString("description");
String urlToImage = jsonPart.getString("urlToImage");
String publish = jsonPart.getString("publishedAt");
String content = jsonPart.getString("content");
DisplayNews(title , urlToImage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) { //we have renamed strings to url
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in); //it adds everything to the bitmap.
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newscontent = new ArrayList<String>();
urlImageContent = new ArrayList<String>();
aboutNews = findViewById(R.id.aboutNews);
//.........................................................................
aboutNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
finalUrl = urlImageContent.get(i);
ImageDownloader task1 = new ImageDownloader();
try {
myImage = task1.execute(finalUrl).get();
newnewImage.setImageBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//.........................................................................
downloadTask task = new downloadTask();
try {
task.execute("https://newsapi.org/v2/top-headlines?country=in&apiKey=API_KEY");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have created an activity where there is a recycler view that is supposed to show the last games played. It loads the data but when i want to go back to the previous activity the app freezes.
For what I have tried I believe the problem is the thread I use inside the onBindViewHolder method of the adapter, since if i delete the thread and the content inside it the app doesn't freeze.
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
Match match = listMatches.get(position);
final Holder holder = (Holder) viewHolder;
holder.score.setText(match.getKills() + "/" + match.getDeaths() + "/" + match.getAssists());
holder.queue.setText(getQueueName(match.getQueue()));
try {
final String imageUrl = getChampImg(match.getChampId());
final String imageSum1Url = getSumImg(match.getSummoner1());
final String imageSum2Url = getSumImg(match.getSummoner2());
final String imageObj1Url = getObjImg(match.getItem1());
final String imageObj2Url = getObjImg(match.getItem2());
final String imageObj3Url = getObjImg(match.getItem3());
final String imageObj4Url = getObjImg(match.getItem4());
final String imageObj5Url = getObjImg(match.getItem5());
final String imageObj6Url = getObjImg(match.getItem6());
final boolean win = match.getMatchResult();
try {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
if (win == true) {
holder.background.setBackgroundColor(ContextCompat.getColor(context, R.color.colorBackground));
} else {
holder.background.setBackgroundColor(Color.RED);
}
//CHAMP IMAGE
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl).getContent());
holder.imageChamp.setImageBitmap(bitmap);
//SUMS
Bitmap bitmapSum1 = BitmapFactory.decodeStream((InputStream) new URL(imageSum1Url).getContent());
holder.sum1.setImageBitmap(bitmapSum1);
Bitmap bitmapSum2 = BitmapFactory.decodeStream((InputStream) new URL(imageSum2Url).getContent());
holder.sum2.setImageBitmap(bitmapSum2);
//ITEMS
if (imageObj1Url.length() > 1) {
Bitmap bitmapObj1 = BitmapFactory.decodeStream((InputStream) new URL(imageObj1Url).getContent());
holder.item1.setImageBitmap(bitmapObj1);
}
if (imageObj2Url.length() > 1) {
Bitmap bitmapObj2 = BitmapFactory.decodeStream((InputStream) new URL(imageObj2Url).getContent());
holder.item2.setImageBitmap(bitmapObj2);
}
if (imageObj3Url.length() > 1) {
Bitmap bitmapObj3 = BitmapFactory.decodeStream((InputStream) new URL(imageObj3Url).getContent());
holder.item3.setImageBitmap(bitmapObj3);
}
if (imageObj4Url.length() > 1) {
Bitmap bitmapObj4 = BitmapFactory.decodeStream((InputStream) new URL(imageObj4Url).getContent());
holder.item4.setImageBitmap(bitmapObj4);
}
if (imageObj5Url.length() > 1) {
Bitmap bitmapObj5 = BitmapFactory.decodeStream((InputStream) new URL(imageObj5Url).getContent());
holder.item5.setImageBitmap(bitmapObj5);
}
if (imageObj6Url.length() > 1) {
Bitmap bitmapObj6 = BitmapFactory.decodeStream((InputStream) new URL(imageObj6Url).getContent());
holder.item6.setImageBitmap(bitmapObj6);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
adminpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.dataList);
Button button = (Button) findViewById(R.id.rf);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
}
});
}
public static class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String movieName = finalObject.getString("movie");
int year = finalObject.getInt("year");
finalBufferedData.append(movieName + " - " + year + "\n");
}
//JSONObject finalObject = parentArray.getJSONObject(0);
return finalBufferedData.toString();
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mTextView.setText(result);
}
}
So base on this what i can conclude is.
1) JSONTASK will take the url and break them in to different string and link them together and return finalBufferedData.toString();
2) The onPostExecute will take the result and set it to mTextView.
3) onclicklistener will run the function and perform step 2 and display.
Question!
I don't see anywhere in the code that call the function onPostExecute(String result) <-- what is the result?? is it the return finalBufferedData.toString()?
I am running the same function in another activity, how do i display in TextView without the onClicklistener to execute it.
1. Yes.. it is the return value(finalBufferedData.toString()).It is the output (result/return) of doInBackground method.
2. Call in onCreate or onResume for executing without onClick. eg:-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// put the AsyncTask call here
I have a url "yyyyyyy.com/test.txt", which is a text file.
It contains urls of .mp3 audios.
yyyyyyy.de/1.mp3
yyyyyyy.de/2.mp3
yyyyyyy.de/3.mp3 //exactly like that
My intention was to read each line of this text file and store it in an array like
urls[0]=yyyyyyy.de/1.mp3
urls[1]=yyyyyyy.de/2.mp3 ...
this.
String[] urls;
int i=0;
Random rand;
int min=0;
int max=5; // I have 6 Urls in the text file
int randomNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rand = new Random();
randomNum = rand.nextInt((max - min) + 1) + min; //generates integer between 0-5
try {
// Create a URL for the desired page
URL url = new URL("yyyyy.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
urls[i]=str;
i++;
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
boolean isPLAYING = false;
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(urls[randomNum]);
mp.prepare();
mp.start();
} catch (IOException e) {
}
} else {
isPLAYING = false;
}
}
I have already add in Manifest.xml the android:permission.
I don't know where the problem is...the app closes itself and tells me
that this line " mp.setDataSource(urls[randomNum]);" is wrong
Here LogCat : http://textuploader.com/5iw5b
Thanks in advance !!
Your array is NULL
put this code after super.onCreate
urls=new String[max]
Update 3:
try this:
ArrayList<String> urls=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Create a URL for the desired page
URL url = new URL("yyyyy.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Log.i("test","url count="+urls.size());
boolean isPLAYING = false;
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
int randomPos = new Random().nextInt(urls.size());
mp.setDataSource(urls.get(randomPos));
mp.prepare();
mp.start();
} catch (IOException e) {
}
} else {
isPLAYING = false;
}
}