Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Hi, Java Android beginner. I am making a chat app for my assignment. I get to the end and crash. I tried to figure out

Hi, Java Android beginner. I am making a chat app for my assignment. I get to the end and crash. I tried to figure out what is causing this but I can't see what am I missing. Any help is appreciated. I need to have my data get on the gui when firing the emulator but that's when the crash happens. This is my code, please help me repair the crash.

import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { EditText etxtPostMsg; Button btnPost; TextView txtReceivedPosts; Handler myFetchPostsHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar=( Toolbar ) findViewById(R.id.toolbar); setSupportActionBar(toolbar); 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(); } }); etxtPostMsg=( EditText ) findViewById(R.id.etxtPostMsg); btnPost=( Button ) findViewById(R.id.btnPost); txtReceivedPosts=( TextView ) findViewById(R.id.txtReceivedPosts); btnPost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = etxtPostMsg.getText().toString(); etxtPostMsg.setText(""); Log.d("MyMsg", "Message = " + message); //PostMessage(message);  PostTask postTask = new PostTask(); postTask.execute("Susan", message); } }); myFetchPostsHandler=new Handler(); myFetchPostsHandler.postDelayed(myFetchPostsTimerRunnable, 2000); } // Run this method on a regular interval.  private Runnable myFetchPostsTimerRunnable = new Runnable() { @Override public void run() { Log.d("MyRecMsg", "myFetchPostsTimerRunnable"); // Do Something Great!!!  FetchPostsTask fetchPostsTask; fetchPostsTask = new FetchPostsTask(); fetchPostsTask.execute(); // Reset timer to run again.  myFetchPostsHandler.postDelayed(myFetchPostsTimerRunnable, 1000); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.  getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will  // automatically handle clicks on the Home/Up button, so long  // as you specify a parent activity in AndroidManifest.xml.  int id=item.getItemId(); /oinspection SimplifiableIfStatement  if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } // android.os.AsyncTask  // Params: The type of parameters sent to the task upon execution.  // Progress: The type of the progress units published during the background computation.  // Result: The type of the result of the background computation.  public class PostTask extends AsyncTask  { @Override protected String doInBackground(String... params) { Log.d("MyMsg", "PostTask AsyncTask"); // If there is a message to post, then there's nothing to do.  // Verify the size of the params.  if (params.length == 0) { return null; } Log.d("MyMSg", "Username = " + params[0]); Log.d("MyMSg", "Post = " + params[1]); // These lines need to be declared outside of the try/catch block  // so that they can be closed in the finally  HttpURLConnection urlConnection=null; BufferedReader reader=null; // will contain the raw received response as a string.  String receivedResponseStr=null; try { // Construct the URL for the message to be posted to the database.  // No parameter need to be passed.  // http://testchat.ridgewater.net/postmessageandroid.php?   final String BASE_URL="http://testchat.ridgewater.net/postmessageandroid.php?"; final String USERNAME_PARAM="txtUserName"; // after ? it's looking for a parameter called txtUserName  final String CHATMESSAGE_PARAM="txtChatMessage"; Uri builtUri=Uri.parse(BASE_URL).buildUpon() .appendQueryParameter(USERNAME_PARAM, params[0]) .appendQueryParameter(CHATMESSAGE_PARAM, params[1]) .build(); URL url=new URL(builtUri.toString()); Log.d("MyMsg", "url = " + url); // Create the request to testchat.ridgewater.net, and open the connection.  urlConnection=( HttpURLConnection ) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); Log.d("MyMsg", "Connection was made."); // Read the input stream into a string.  InputStream inputStream=urlConnection.getInputStream(); StringBuffer buffer=new StringBuffer(); if (inputStream == null) { // Nothing to do.  receivedResponseStr="No input stream."; } reader=new BufferedReader(new InputStreamReader(inputStream)); String line; Boolean endOfFile; endOfFile=false; while (!endOfFile) { line=reader.readLine(); if (line == null) { endOfFile=true; } else { buffer.append(line + " "); } } if (buffer.length() == 0) { receivedResponseStr="Empty stream."; } receivedResponseStr=buffer.toString(); Log.d("MyMsg", "receivedResponseStr = " + receivedResponseStr); } catch (IOException e) { Log.d("MyMsg", "Error = ", e); receivedResponseStr=null; } finally { if (urlConnection != null) { urlConnection.disconnect(); Log.d("MyMsg", "Connection is closed."); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.d("MyMsg", "Error closing stream", e); } } } // end try/catch/finally block   return null; } // end do inBackground method  } // end PostTask   // android.os.AsyncTask  // Params: The type of parameters sent to the task upon execution.  // Progress: The type of the progress units published during the background computation.  // Result: The type of the result of the background computation.  public class FetchPostsTask extends AsyncTask  { @Override protected String doInBackground(String... params) { Log.d("MyRecMsg", "FetchPostsTask AsyncTask"); // These lines need to be declared outside of the try/catch block  // so that they can be closed in the finally  HttpURLConnection urlConnection = null; BufferedReader reader = null; // will contain the raw received response as a string.  String receivedPostsStr = null; try { // Construct the URL for the message to be posted to the database.  // No parameter need to be passed.  // http://testchat.ridgewater.net/getpostsandroid.php?   final String BASE_URL="http://testchat.ridgewater.net/getpostsandroid.php?"; Uri builtUri=Uri.parse(BASE_URL).buildUpon() .build(); URL url = new URL(builtUri.toString()); Log.d("MyRecMsg", "url = " + url); // Create the request to testchat.ridgewater.net, and open the connection.  urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); Log.d("MyRecMsg", "Connection was made."); // Read the input stream into a string.  InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do.  receivedPostsStr = "No input stream."; } reader=new BufferedReader(new InputStreamReader(inputStream)); String line; Boolean endOfFile; endOfFile=false; while (!endOfFile) { line=reader.readLine(); if (line == null) { endOfFile=true; } else { buffer.append(line + " "); } } if (buffer.length() == 0) { receivedPostsStr = "Empty stream."; } receivedPostsStr = buffer.toString(); Log.d("MyRecMsg", "receivedPostsStr = " + receivedPostsStr); } catch (IOException e) { Log.d("MyRecMsg", "Error = ", e); receivedPostsStr = "IOException - Network Failure."; } finally { if (urlConnection != null) { urlConnection.disconnect(); Log.d("MyRecMsg", "Connection is closed."); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.d("MyRecMsg", "Error closing stream", e); } } } // end try/catch/finally block   return receivedPostsStr; } // end do inBackground method   @Override protected void onPostExecute(String result){ Log.d("MyRecMsg", "*** In OnPostExecute ***"); if (result != null){ txtReceivedPosts.setText(result); } } } // end PostTask  } // end MainActivity classimage text in transcribed

04-04 02:30:57.632 9436-9436/com.positiveid.mobilechatrevised E/AndroidRuntime: FATAL EXCEPTION: main Process: com.positiveid.mobilechatrevised, PID: 9436 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText (java.lang.CharSequence)' on a null object refer at com.positiveid.mobilechatrevised.MainActivitysFetchPostsTask.onPostExecute (MainActivity.java:281) at com.positiveid .mobilechatrevised .MainActivity$FetchPostsTask.onPostExecute (Main ctivity. va: 200) at android.os.AsyncTask.finish (AsyncTask.java: 667) at android.os.AsyncTask.-wrapl (AsyncTask.java) at android.os.AsyncTasksInternalHandler.handleMessage (AsyncTask.java: 684) at android.os . Handler.dispatchMessage (Handler.java: 102) at android.os.Looper.loop (Looper.java:154) at android.app.ActivityThread.main (ActivityThread.java: 6119) at com.android.internal.os.ZygoteInitMethodAndArgsCaller.run (ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java: 776) 03

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning Microsoft SQL Server 2012 Programming

Authors: Paul Atkinson, Robert Vieira

1st Edition

1118102282, 9781118102282

More Books

Students also viewed these Databases questions

Question

2. Establish eye-level position.

Answered: 1 week ago

Question

3 What are the stages of Kotter and Cohens model of change?

Answered: 1 week ago

Question

4 What is organisation development?

Answered: 1 week ago

Question

5 What activities are employed in OD processes?

Answered: 1 week ago